File, directory operations related functions

One. File manipulation functions

1.stat function

1.1 stat records the information file

 

 

1.2 st_mode by a 16-bit binary number, as shown below:

The following figure shows the various octal file type will be obtained st_mode & 0170000 file type to a file is not determined normal file:

struct stat st;

stat("123.txt",&st);

if((st.st_mode&S_IFMT)==S_IFREG)

{

printf ( "This is a regular file");

}

 

 

 1.3 Calculation type file permissions follows:

 Further reference may be: https: //blog.csdn.net/astrotycoon/article/details/8679676

 

2.lstat function

3.chmod

4.chown

uid and gid can be viewed in vi / etc / passwd in

 

5.truncate

6.link

7.rename

8.dup dup2 

To copy a file descriptor 

Prototype:

The minimum 1.dup oldfd copy file descriptors available, and returns

Example program: ret write and the file descriptor fd may by conventional a.txt data file, and the file pointer is not restored.

 

2.dup2 will oldfd copied as newfd

The sample program: The original "english.txt" copy of the file descriptor fd is fd1, namely a.txt file descriptors, and write data to a.txt

 

 

 

 

9.fcntl

Get file status when an incoming F_GETFL cmd, arg = 0;

An incoming file status F_SETFL cmd, arg = flag;

 

 

II. Directory manipulation functions

1.chdir 和 getcwd 

2.mkdir 和 rmdir 

3.opendir

 

4.readdir

//递归读取子目录并计算普通文件个数
#include<stdio.h> #include<stdlib.h> #include<dirent> int getFileNum(const char *filename) { DIR *dir=NULL; dir=opendir(filename); struct dirent* ptr=NULL; if(dir==NULL) { perror("opendir"); exit(1); } char path[1024]={0}; while((ptr=readdir(dir))!=null) { //过滤.和.. if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0) { continue; } //如果是目录 if(ptr->d_type==DT_DIR) { sprintf(path,"%s%s",filename,ptr->d_name); //递归读目录 total+=getFileNum(path); } //如果是普通文件 if(ptr->d_type==DT_REG) { total++; } } closedir(dir); return total; } int main(int argc,char* argv[]) { int total=getFileNum(argv[1]); printf("%s has file numbers %d",argv[1],total); return 0; }

  

5.closedir

 

Guess you like

Origin www.cnblogs.com/sclu/p/11246003.html