linux下文件编程

stat获取文件属性时需要用绝对路径,否则返回的是NULL

#include 
#include 
#include 
#include 
#include 
#include 
int readFileList(char *basePath,char *find_str)
{
    DIR *dir;
    struct dirent *ptr;
     char base[1000];
    struct stat statbuf;
 
     if ((dir=opendir(basePath)) == NULL)
     {
         perror("Open dir error...");
         exit(1);
     }
 
     while ((ptr=readdir(dir)) != NULL)
     {
    //printf("read dir %c, %s\n",ptr->d_type,ptr->d_name);
    char *filename=malloc(strlen(basePath)+strlen(ptr->d_name)+1);
    strcpy(filename,basePath);
    strcat(filename,ptr->d_name);
    stat(ptr->d_name,&statbuf);
    stat(filename,&statbuf);
    if(S_ISREG(statbuf.st_mode))
    {
        printf("%s\n",ptr->d_name);
        if(strstr(ptr->d_name,find_str) != NULL)
            printf("with: %s %s\n",find_str,ptr->d_name);
    }
    free(filename);
    /*
    if(S_ISDIR(statbuf.st_mode))
    {   
        printf("dir:%s\n",ptr->d_name); 
    }*/

     }
     closedir(dir);
     return 1;
 }
 
 int main(int argc, char **argv)
 {
     DIR *dir;
     char basePath[1000];

     readFileList("/opt/",argv[1]);
     return 0;
 }

你可能感兴趣的:(linux下文件编程)