【问题标题】:How to read name of files in a directory, and counting the words and line如何读取目录中的文件名,并计算单词和行
【发布时间】: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,也许还有其他一些。不要让我们假设一件事。
  • 请再问一个问题。这个网站不是一个滚动的“修复我的代码”的地方!

标签: c file


【解决方案1】:

这是你的 while 循环

        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);
}

with fclose(fp); inside 正在从中读取的循环。格式化后,您的代码是

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);
}

现在,您可以看到需要将fclose(fp); 移出循环。

【讨论】:

  • 即使对于常规文本文件,ch 永远不会为零,ch = '\0' 是可疑的。也就是说,在您答案的最后一段代码中。如果有人在不考虑所有“滚动”问题的情况下复制了这段代码,我会很难过。
猜你喜欢
  • 2016-08-06
  • 1970-01-01
  • 2021-06-25
  • 2018-08-07
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 1970-01-01
相关资源
最近更新 更多