如何在C中将.txt文件扫描成字符?

时间:2019-05-21 12:32:30

标签: c fseek fgetc

我希望能够将文本文件扫描到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文件。

1 个答案:

答案 0 :(得分:0)

您需要进行以下更改

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

  2. 使 documentStore 为char指针,并使用 malloc 分配 size

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

相关问题