在 C 中使用 fgetc 读取文件

File reading with fgetc in C

我有一个简单的文件读取算法,但它没有返回文件中的值。下面是代码。输入的 txt 值为 200 53 65 98 183 37 122 14 124 65 67 但代码返回 48 48 32 53 51 32 54 53 32 57 56 32 49 56 51 32 51 55 32 49 50 50 32 49 52 52 32 52 32 52 32 54 53 32 54 55 -1 我不确定为什么。

应该是把读入的值读入链表中

int readInputFile(char *fileName, LinkedList *list)
{
    FILE *inputFile = fopen(fileName, "r");
    int ch;

    if (inputFile == NULL)
    {
        perror("Could not open file");
    }
    else
    {
        while (ch != EOF)
        {
            ch = fgetc(inputFile);
            printf("%d", ch);
            if (ferror(inputFile))
            {
                perror("Error reading from source file.");
            }
            else
            {
                //printf("%d", ch);
                insertLast(list, ch);
            }
        }
    }
}

您使用 fgetc() 读取一个字符,但您想要读取一个数字,而您使用 int d; fscanf(inputFile, "%d", &d) 读取一个数字。

您的代码有未定义的行为,因为您第一次测试 while (ch != EOF)ch 未初始化。你应该写:

    while ((ch = fgetc(inputFile)) != EOF) {
        [...]

但问题是您读取的是单个字节,而不是解析文件内容以获取以十进制整数表示的数字。您应该使用 fscanf() 将文本转换为整数。

您还忘记关闭文件,导致资源泄露

这是修改后的版本:

#include <errno.h>
#include <stdio.h>
#include <string.h>

int readInputFile(const char *fileName, LinkedList *list)
{
    FILE *inputFile = fopen(fileName, "r");

    if (inputFile == NULL) {
        fprintf(stderr, "Could not open file %s: %s\n",
                fileName, strerror(errno));
        return -1;
    } else {
        int value, count = 0;
        char ch;
        while (fscanf(inputFile, "%d", &value) == 1) {
            printf("inserting %d\n", value);
            insertLast(list, value);
            count++;
        }
        if (fscanf(inputFile, " %c", &ch) == 1) {
            fprintf(stderr, "File has extra bytes\n");
        }
        fclose(inputFile);
        return count;  // return the number of integers inserted.
    }
}