【问题标题】:How to scan in a .txt file into a char in C?如何将 .txt 文件扫描成 C 中的字符?
【发布时间】: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 &lt; size; j++) -> for (int j = 0; j &lt; i; j++) 因为你应该循环直到最后一个字符被分配而不是整个数组
  • 肯定有一些家庭作业,最近有几个关于阅读文件、存储文本和处理大写字母的问题。
  • 提示:你知道要读取的文件的大小,那你为什么要逐个字符地读取文件呢?您应该使用fread 读取整个文件。
  • "目前我得到了很多随机...字符" --> 验证 inputFile 不是 NULL

标签: c fseek fgetc


【解决方案1】:

您需要进行以下更改

  1. int size = ftell(inputFile); 之后添加 fseek(inputFile, 0, SEEK_SET); 按照 xing 的建议

  2. documentStore 设为 char 指针并使用 ma​​llocsize 值分配内存

  3. while(feof(inputFile)) 必须改为 while(!feof(inputFile))

【讨论】:

    猜你喜欢
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    相关资源
    最近更新 更多