簡體   English   中英

在 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) int d; fscanf(inputFile, "%d", &d)

您的代碼具有未定義的行為,因為您在第一次未初始化ch的情況下測試while (ch != EOF) 你應該寫:

    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.
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM