【发布时间】:2019-10-07 20:28:25
【问题描述】:
我希望能够将文本文件扫描到我的 C 程序中,这样我就可以搜索和存储包含大写字母的单词。我的问题是扫描文件。
我尝试通过使用 fseek 来确定文本文件的长度并使用 char[] 创建数组来创建字符串。然后我尝试使用 fgetc 将每个字符扫描到数组中,但这似乎不起作用。最后的 for 循环通过打印出来来验证扫描是否有效。
#include <stdio.h>
int main() {
FILE *inputFile;
inputFile = fopen("testfile.txt", "r");
//finds the end of the file
fseek(inputFile, 0, SEEK_END);
//stores the size of the file
int size = ftell(inputFile);
char documentStore [size];
int i = 0;
//stores the contents of the file on documentstore
while(feof(inputFile))
{
documentStore[i] = fgetc(inputFile);
i++;
}
//prints out char
for (int j = 0; j < size; j++)
{
printf("%c", documentStore[j]);
}
return 0;
}
目前我得到了很多随机的 ascii 字符,我不知道为什么。我希望 for 循环打印出整个 txt 文件。
【问题讨论】:
-
int i = 0; while(feof(inputFile)) { documentStore[i] = fgetc(inputFile);->int i = 0, c; while((c = fgetc(inputFile)) != EOF) { documentStore[i] = c;见Why is “while (!feof(file))” always wrong?。另外,for (int j = 0; j < size; j++)->for (int j = 0; j < i; j++)因为你应该循环直到最后一个字符被分配而不是整个数组 -
肯定有一些家庭作业,最近有几个关于阅读文件、存储文本和处理大写字母的问题。
-
提示:你知道要读取的文件的大小,那你为什么要逐个字符地读取文件呢?您应该使用
fread读取整个文件。 -
"目前我得到了很多随机...字符" --> 验证
inputFile不是NULL。