【发布时间】:2021-09-14 09:48:33
【问题描述】:
您好,我必须列出目录中的文件,并且对于每个文件,我会计算字数和行数。问题出在打开文件上,因为文件指针始终为 NULL。 文件位于此文件夹中:myfolder,程序也是。
程序从这里启动:otherthings/myfolder/readfiletest.c
int main(void)
{
int word_count = 0, line_count = 0,in_word = 0;
char ch;
DIR *d;
FILE *fp;
char path[2100];
struct dirent *dir;
d = opendir("myfolder");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
strcpy(path,"myfolder");
strcat(path,"/");
strcat(path,dir->d_name);
fp = fopen(path, "r");
int i =0;
/*while(path[i]){
printf("%c",path[i]);
i++;
}*/
if(fp == NULL) {
perror("Could not open the file");
}
while ((ch = fgetc(fp)) != EOF) {
if(ch == ' ' || ch == '\t' || ch == '\0' || ch == '\n') {
if (in_word) {
in_word = 0;
word_count++;
}
if(ch = '\0' || ch == '\n') line_count++;
} else {
in_word = 1;
}
fclose(fp);
}
}
printf("Number of words: %d.\n", word_count);
printf("Number of lines: %d.\n", line_count);
closedir(d);
}
return(0);
}
编辑的代码,我的输出是: 我的文本.txt .. . 分段错误(我无法报告异常,因为我在包含 OpenMPI 环境的容器中运行,所以错误是 mpirun 注意到节点 979208abf4bc 上的进程等级 0 和 PID 0 在信号 11 上退出(分段错误) )。
【问题讨论】:
-
"myfolder"似乎在可见路径上,所以一个文件会有"myfolder/mytext.txt",而不是"mytext.txt"? -
所以我应该打开阅读 myfolder/mytext.txt? @WeatherVane
-
这就是暗示:尝试从文件夹和文件名中构造名称。
-
不是迂腐,但你需要
#include <stdio.h>和string.h,也许还有其他一些。不要让我们假设一件事。 -
请再问一个问题。这个网站不是一个滚动的“修复我的代码”的地方!