0

我正在尝试用c编写一个程序,该程序接受一个目录并循环遍历目录中的文件。我计划对文件进行一些处理并以新名称重新保存它们。我使用 dirent 结构来获取目录内容,但是当我尝试从 dirent 中获取 FILE * 时出现问题。

 1 #include <unistd.h>
 2 #include <sys/types.h>
 3 #include <dirent.h>
 4 #include <stdio.h>
 5 #include <string.h>
 6 #include <sys/fcntl.h>
 7 #include <stdlib.h>
 8 #include <sys/stat.h>
 9 #include <errno.h>
 13 char parentName[256];
 14 
 15 void listdir(const char *name, int level)
 16 {
 17     DIR *dir;
 18     struct dirent *entry;
 19 
 20     if (!(dir = opendir(name)))
 21         return;
 22     if (!(entry = readdir(dir))){
 23         closedir(dir);
 24         return;
 25     }
 26 
 27     do {
 28         if (entry->d_type == DT_DIR) {
 29                 printf("Don't give me a directory!!");
 30         }
 31         else{
 32                 FILE *thisFile;
 33                 if(!(thisFile = fopen(entry->d_name, "r"))){
 34                         printf("Error");
 35                 }
 36                 struct stat buf0;
 37                 fstat(fileno(thisFile), &buf0);
 38                 off_t size = buf0.st_size;
 39                 printf("size = %d\n",(int) size);
 40                 printf("Made it here first");
 41                 char *buf1 = (char*) malloc(101);
 42                 printf("Made it here");
 43                 fgets(buf1,100,thisFile);
 55                 printf("%s",buf1);
 56         }
 57     } while ((entry = readdir(dir)));
 58     closedir(dir);
 59 }
 60 
 61 int main(int argc, char* argv[])
 62 {
 63         if (argc == 0)  listdir(".", 0);
 64         else listdir((char*)argv[1],0);
 65     return 0;
 66 }

程序输出

大小 = 12292
分段错误:11

如果我删除第 39 行,它只是段错误。(此外,该大小与文件大小(以字节、字符或字为单位)不接近。)请帮忙,谢谢!

:)

编辑:包括#includes

4

1 回答 1

2

我看到三个问题:

  1. argc当您不提供任何参数时,是 1 而不是 0。所以,main()改为:

    if (argc == 1) listdir(".", 0);

  2. 失败时fopen(),您仍然尝试处理该文件。添加一个elsecontinue循环:

    if(!(thisFile = fopen(entry->d_name, "r"))){
    printf("Error");
    continue;
    }

  3. 你有内存泄漏。你分配buf1,但你从来没有free()

于 2012-11-14T07:40:47.437 回答