如何将 .txt 文件扫描到 C 中的字符中?
How to scan in a .txt file into a char in C?
我希望能够将文本文件扫描到我的 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 size = ftell(inputFile);之后添加fseek(inputFile, 0, SEEK_SET); 根据 xing
的建议
使 documentStore 成为字符指针并使用 malloc 为 size[=29 分配内存=]值
while(feof(inputFile)) 必须改为 while(!feof(inputFile))
我希望能够将文本文件扫描到我的 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 size = ftell(inputFile);之后添加fseek(inputFile, 0, SEEK_SET); 根据 xing
的建议
使 documentStore 成为字符指针并使用 malloc 为 size[=29 分配内存=]值
while(feof(inputFile)) 必须改为 while(!feof(inputFile))