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