一 递归获取文件及其子文件
readir.c文件
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
int readir(const char * path)
{
DIR * dir;
struct dirent * ptr;
char *newPath;
printf("Search Path name: %s/n/n",path);
if ((dir = opendir(path)) == NULL) {
perror("opendir");
return -1;
}
while ((ptr = readdir(dir))!=NULL)
{
printf("file name: %s",ptr->d_name);
printf(" file type: %d/n",ptr->d_type);
if(strcmp(ptr->d_name,".")==0) continue;
if(strcmp(ptr->d_name,"..")==0) continue;
if(ptr->d_type!=4) continue; //非目录
newPath=(char*)malloc(strlen(ptr->d_name)+strlen(path)+2);
strcpy(newPath,path);
strcat(newPath,ptr->d_name);
strcat(newPath,"/");
readir(newPath);
free(newPath);
}
closedir(dir);
return 0;
}
int main(int argc, char ** argv)
{
if (argc < 2) {
printf("please input path/n");
return 1;
}
if (readir(argv[1]) < 0) {
return 1;
}
return 0;
}
执行命令 ./readir /yourpath
二 查询文件属性,文件大小类型修改时间创建时间等...
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
int main(int argc, char *argv[])
{
struct stat buf;
if (argc != 2) {
printf("Usage: my_stat <filename>/n");
return -1;
}
if ( stat(argv[1], &buf) == -1 ) { //使用文件句柄方式可用 int fstat(int filedes,struct stat *buf);
perror("stat:");
return -1;
}
printf("device is: %d/n", (int)buf.st_dev);
printf("inode is: %d/n",(int) buf.st_ino);
printf("mode is: %o/n", buf.st_mode);
printf("number of hard links is: %d/n", buf.st_nlink);
printf("user ID of owner is: %d/n", buf.st_uid);
printf("group ID of owner is: %d/n", buf.st_gid);
printf("device type (if inode device) is: %d/n", (int)buf.st_rdev);
printf("total size, in bytes is: %d/n", (int)buf.st_size);
printf(" blocksize for filesystem I/O is: %d/n",(int) buf.st_blksize);
printf("number of blocks allocated is: %d/n",(int) buf.st_blocks);
printf("time of last access is: %s", ctime(&buf.st_atime));
printf("time of last modification is: %s", ctime(&buf.st_mtime));
printf("time of last change is: %s", ctime(&buf.st_ctime));
return 0;
}
S_ISLNK(st_mode):是否是一个连接.S_ISREG 是否是一个常规文件.S_ISDIR 是否是一个目录 S_ISCHR 是否是一个字符设备.S_ISBLK 是否是一个块设备 S_ISFIFO 是否 是一个 FIFO文件.S_ISSOCK 是否是一个 SOCKET 文件.
三 移动文件(相当于mv)
int rename (__const char *__old, __const char *__new);
四 文件删除
int remove (__const char *__filename);