【发布时间】:2015-07-27 17:48:23
【问题描述】:
我正在尝试 1)查找目录中的所有文件并显示它们,2)打开所有找到的文件并从中读取数据(字符) 3)将读取的数据输出到屏幕或新文件。
这是用 C 语言完成的,您将在下面看到我当前的代码。我遇到的问题是:我可以在我的目录中找到所有文件并将它们打印到屏幕上就好了(上面的第 1 点),但是当我尝试打开找到的文件并从中读取数据(字符)时(上面的第 2 点),我遇到了分段错误。
如果我注释掉下面的fscanf(entry_file, "%s", files); 行,但留下entry_file = fopen(in_file->d_name, "r"); 行,它编译正常并将文件写入屏幕。我还尝试使用int i(未在下面显示)索引fscanf 行并产生相同的分段错误。
那么,如何从这些找到的文件中读取数据?谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
int main()
{
DIR* dir;
FILE *entry_file;
struct dirent *in_file;
char files[1000];
int i;
dir = opendir("/Users/tcn/data");
if(dir==NULL){
printf("Error! Unable to read directory");
exit(1);
}
while( (in_file=readdir(dir)) != NULL) {
if (!strcmp (in_file->d_name, "."))
continue;
if (!strcmp (in_file->d_name, ".."))
continue;
printf("%s\n", in_file->d_name);
entry_file = fopen(in_file->d_name, "r");
fscanf(entry_file, "%s", files);
}
closedir(dir);
fclose(entry_file);
return 0;
}
【问题讨论】:
-
我不认为这是问题所在,但您应该在循环中关闭您的
entry_file。 -
entry_file = fopen(in_file->d_name, "r");需要检查返回值。(可能需要文件的完整路径)还需要fclose每个文件。 -
files只能容纳1000字节,也许您的一个或多个文件有更多?此外,您正在打开所有文件而不是关闭它们。您可以同时打开多少个文件是有限制的。另外,检查文件的打开是否成功,如果我没记错的话,in_file->d_name只是文件的基本名称,您必须将/Users/tcn/data/附加到文件名的开头才能将其传递给fopen()否则fopen()将找不到该文件。您可以使用chdir()来解决此问题(您只需调用一次)。 -
您应该在使用之前检查
entry_file是否有NULL,如果不是NULL,则应该在之后检查fclose。