begin linux programming

来源:互联网 发布:淘宝手机端购买流量 编辑:程序博客网 时间:2024/06/07 02:35
Recently,i begin to learn programming in linux , so i choose the book with the name of <<Begin linux programming>> as my first book of exploiting programming under linux . here , i will list some of the basic operations under linux to let you get involved in linux as soon as possible. also , the sequence of my blogging will begin with files.

In this chapter , you will know how to manipulate the files and the directories , you will learn how to open , read , write ,close them, and also the property of the file you are interested , lastly, we will take a close look at how to scan the directories under linux.

first of all, i just want to show you some basic function used in linux to manipulate fhe file.(i just wish you know that almost everything in linux is a file , so you can use the same way to manipulate the one you want):

int open(const char * path , int oflags);int open(const char * path , int oflags , mode_t mode);



in simple terms , the open function establishes an access path to a file or device which is lead by path, and the oflags take the parameter of "R_RDONLY , O_WRONLY , O_RDWR , O_APPEND , O_TRUNC , O_CREAT , O_EXCL" as for the meaning of each parameter , i do suggest you look for the meaning  yourself by using the command of " man 2 open " under the terminals. by the way ,<fcntl.h> , <sys/types.h> <sys/stat.h> must be included ( strcitly speaking , there is no need including <sys/..> but the may be necessary on some UNIX system.


size_t read(int fildes , void * buffer , size_t nbytes);size_t write(int fildes , const void * buf , size_t nbytes);



the read() and write() function are similar , so we just need to specify one , take the read() function as an example , the fildes it an nonnegaticve integer with the  type of int which is returned by open() function, and the buf refers to the buffer which will contain the content you read from the file , nbytes means the number you want to read from the file in bytes , last the return value means the real number of bytes you read from the file. don't forget the <unistd.h> when you want to use it , similar to write() function.

int close(int fildes);


close the file you have open with the parameter of fildes you get from open() function.

NOTE: never use a parameter with the name of " write , read , close , or something else " for that you will meet the error like this
"called object is not a function " if you insist on.

come with an example :




next i want to show you some other system calls which can be used to manipulate the file and also get the detailed property of the file

off_t lseek(int fildes , off_t offset , int whence);


the fildes is determined by the fildes and the offset parameter is used to specify the position , and the whence parameter specifies how the offset is used , whence can be one of the following :
SEEK_SET   :  offset is an absolute position
SEEK_CUR   :  offset is relative to the current position
SEEK_END   :  offset is relatice to the end of the file

and the return value is measured in bytes from the beginning of the file that the file pointer is set to or -1ib failure, remember the off_t type is determined in <sys/types.h>

the most useful function about the file manipulation is as follows:

int fstat(int fildes , struct stat * buf)int stat(const char * path , struct stat * buf)int lstat(const char * path , struct stat * buf)


those functions can store the status information in a struct stat structure ,and you can see it below:


 struct stat      {                dev_t       st_dev;     /* ID of device containing file -文件所在设备的ID*/                ino_t       st_ino;     /* inode number -inode节点号*/                mode_t      st_mode;    /* protection -保护模式?*/                nlink_t     st_nlink;   /* number of hard links -链向此文件的连接数(硬连接)*/                uid_t       st_uid;     /* user ID of owner -user id*/                gid_t       st_gid;     /* group ID of owner - group id*/                dev_t       st_rdev;    /* device ID (if special file) -设备号,针对设备文件*/                off_t       st_size;    /* total size, in bytes -文件大小,字节为单位*/                blksize_t   st_blksize; /* blocksize for filesystem I/O -系统块的大小*/                blkcnt_t    st_blocks;  /* number of blocks allocated -文件所占块数*/                time_t      st_atime;   /* time of last access -最近存取时间*/                time_t      st_mtime;   /* time of last modification -最近修改时间*/                time_t      st_ctime;   /* time of last status change - */            };  





and you can see the result of this example to find the useful function stat() function:

suilingxi@ubuntu:~$ ./dir
a regular file
the time of last access :Fri Jan 31 18:04:00 2014

the time of last modification to contents : Wed Jan 22 17:31:35 2014

the number of hard links to the file : 1
suilingxi@ubuntu:~$

now  , let  begin with some other manipulation about the file


int unlink(const char * path);int link(const  char * path1 , const char *path2);int symlink(const char * path1 , const char * path2);


now show you an example:


#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>#include <sys/types.h>#include <sys/stat.h>#include <string.h>int main(){/* establish the link toward the file block*/char path1[]="/home/suilingxi/test";char path2[]="/home/suilingxi/test2";char path3[]="/home/suilingxi/syslink";if(link(path1,path2)==0){printf("link ok\n");}/*read the content from the file test2*/int fildes=open(path2,O_RDONLY);if(fildes==-1){printf("open file test2 error\n");exit(0);}char buffer[100];memset(buffer,0,100);int readed=0;while((readed=read(fildes,buffer,100))>0){printf("the hard link content : %s\n",buffer);}/*establish the syslink toward the file test*/if(symlink(path1,path3)==0){printf("create soft link ok \n");}/*read the content from the soft link syslink*/int value=open(path3,O_RDONLY);if(value==-1){printf("read soft file symlink error\n");exit(0);}char buf[100];memset(buf,0,100);int r=0;while((r=read(value,buf,100))>0){printf("soft link content : %s\n",buf);}if(unlink(path2)==0){printf("delete hard link ok\n");}if(unlink(path3)==0){printf("delete soft link ok\n");}return 0;}


last i met some problems the time when i try scanning the directory , first i will display some basic function and explain them ,then i will come up with some examples i program also the example which written in the book , and compare them so as you can know the difference and make deep understanding into scanning directory:

#include <sys/types.h>#include <sys.stat.h>int mkdir(const char * path, mode_t mode);#include <unistd.h>int rmdir(const char * path);int chdir(const char * path);char * getcwd(char * buf,size_t size);#include <sys/types.h>#include <dirent.h>DIR * opendir(const char * name);struct dirent * readdir(DIR * dirp);long int telldir(DIR * dirp);void seekdir(DIR * dirp, long int loc);int closedir(DIR * dirp);

and i do believe you will use the function fstat(), stat(),lstat() from <unistd.h> <sys/stat.h> <sys/types.h> to get the detailed properity of the direcitory of document you receive from opendir() and readdir() function , so as to judge the target wether a document or a directory.last i want to expalin one function which is very very very important in scanning the directory -------readdir()

struct dirent * readdir(DIR * dirp);

NOTE:
       1,successive calls to readdir return further directory entries , on error and at the end of the directory , readdir returns NULL .
       2,readdir() scanning isn't guaranteed to list all the files in a direcoty if there are other processes creating and deleting files in the         directory at the same time.
       3,to determine further details of a file in a directory , you need to amke a call to stat() fstat() lstat() function.

now show you the examples:


#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <dirent.h>#include <string.h>int deep(char * path,int tab);int main(){char path[]="/home/suilingxi/dir";deep(path,0);return 0;}int deep(char  path[] , int tab){    DIR * d;struct dirent * dir;struct stat * s;/*must allocate the memory , if not , then you will meet the problem like"receive signal SIGSEGV and terminate the process "*/s=(struct stat *)malloc(sizeof(struct stat));d=opendir(path);if(d==NULL){printf("open dir error\n");exit(0);}/*set the path as the current path8*/if(chdir(path)==0){}else{printf("change dir error\n");exit(0);}/*read the dir from the path*/while((dir=readdir(d)) != NULL){if(stat(dir->d_name,s)==0){}else{printf("get prosperity error\n");exit(0);}if(S_ISDIR(s->st_mode)){   if(strcmp(dir->d_name,".")==0){printf("%*s.\n",tab,"");continue;}   if(strcmp(dir->d_name,"..")==0){printf("%*s..\n",tab,"");continue;}printf("%*s%s\n",tab,"",dir->d_name);deep(dir->d_name,tab+6);}else{printf("%*s%s\n",tab,"",dir->d_name);}}chdir("..");closedir(d);return 0;}

remember you must allocate the memory before called lstat() fucntion , and you can see the reason from stackoverflow:

2 down vote accepted

From what I can tell, the error is being caused by your failure to initialize thethis_lstat that gets passed as the second parameter to lstat.

The error string "Bad address" corresponds to the error code EFAULT, which comes from passing an invalid pointer to a system call. So, either the path name being passed tolstat doesn't point to a valid null-terminated string in readable memory, or thestruct stat being passed as the second parameter doesn't point to valid writable memory.

You seem to be passing an unitialized pointer, which is almost certainly pointing to invalid memory. Valgrind doesn't complain because up until the system call, you haven't done anything wrong—only when the kernel tries to access the memory does it realize its invalid.

To fix this, either allocate memory for the struct stat with malloc, or just pass a pointer to a variable on the stack instead of using a pointer:

struct stat this_lstat;lstat(..., &this_lstat);


then i show you another example , in this exmaple you needn't allocate the memory but still can run:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <dirent.h>#include <sys/stat.h>void printdir(char * dir , int depth){DIR * dp;struct dirent * entry;struct stat statbuf;if((dp=opendir(dir))==NULL){fprintf(stderr,"cannot open directory : %s\n",dir);return;}chdir(dir);while((entry=readdir(dp)) != NULL){lstat(entry->d_name,&statbuf);if(S_ISDIR(statbuf.st_mode)){if(strcmp(".",entry->d_name)==0||strcmp("..",entry->d_name)==0)continue;printf("%*s%s/\n",depth,"",entry->d_name);printdir(entry->d_name,depth+4);}elseprintf("%*s%s\n",depth,"",entry->d_name);}chdir("..");closedir(dp);}int main(int argc , char * argv[]){char * topdir=".";/*if(argc>2)*/topdir=argv[1];printf("Directory scan of %s\n",topdir);printdir(topdir,0);printf("done\n");return 0;}

i am so sorry  that i don't know the reason why like this , and if you know , please contact me, appreciate.

0 0
原创粉丝点击