gpt4 book ai didi

C - 读取 .txt 中的新行

转载 作者:行者123 更新时间:2023-11-30 17:25:22 24 4
gpt4 key购买 nike

我正在编写一个程序来读取文件并计算 .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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com