C - 读取 .txt 中的新行

标签 c fopen fgets fread

我正在编写一个程序来读取文件并计算 .txt 有多少个单词。该程序工作正常,问题是如果 txt 有断行,它就会停止读取,所以我必须将所有文本放在一行中。据我所知,问题出在 fgets 中,当它到达 EOF 或新行时,它会停止读取。我的问题是:即使有新行,我如何阅读我的文本?我必须使用 fread() 吗?如果是这样,我会这样做吗?下面是我读取 .txt 并将其放入数组的代码部分。

char linha[10000];
int grandezaStrings = 100000;
int i = 0;
int contadorString = 0;    

    //  This line reads the file.
    fgets (linha, grandezaStrings,myFile);

    // Used for special characters
    setlocale (LC_ALL,"PORTUGUESE");

    // Dynamic array to hold words
    char ** strings = (char **)malloc(grandezaStrings * sizeof (char*));
    char * pch;
    for (i=0;i<grandezaStrings; i++){
        strings[i] = (char *)malloc(100+1);
    }

    // Transfer all the words to my array.
    i = 0;
    pch = strtok(linha, " ,.!?:;()\n");
    while (pch != NULL){
        strlwr(pch);
        strings[i] = pch;
        contadorString++;
        pch = strtok (NULL, " ,.!?:;()\n");
        i++;
    }

非常感谢!

最佳答案

fgets 读取到下一个新行。这是设计的。您可以循环 (while (fgets(...) != NULL)),或者如果您想在一次读取中加载内存中的所有内容,您只需使用 fread:

//  This line reads the whole file.
i = fread (linha, 1, grandezaStrings,myFile);
if (i < 0) { // test read Ok
    perror("Lettura");
    return 1;
}
linha[i] = '\0';  // add the terminating null

关于C - 读取 .txt 中的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27080370/

相关文章:

c++ - 在 CMAKE 中添加 -fPIC 编译器选项的惯用方式是什么?

c - 用 C fopen 保存文件

c - 消息 UDP 中的文件名

c - 在 Xcode 上运行 C 程序时,出现错误 - 线程 1 : EXC_BAD_ACCESS (code=1, 地址=0x68)

C fopen 和 fgets 返回奇怪的字符而不是文件内容

c - 读取文件时出现段错误

c - 如何区分可执行文件和自动运行文件

c - 如何解析文本输入并将字符串转换为整数?

代码在 C 中未按预期工作

c - 使用 dSFMT 进行随机 float (0,1)