简体   繁体   中英

File reading with fgetc in C

I have a simple file reading algorithm but it's not returning the values that are in the file. The below is the code. The input txt values are 200 53 65 98 183 37 122 14 124 65 67 but the code is returning 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 32 49 50 52 32 54 53 32 54 55 -1 and I'm not sure why.

It should be taking the read in values and putting it into the linked list.

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);
            }
        }
    }
}

You read a character with fgetc() but you want to read a number which you do with int d; fscanf(inputFile, "%d", &d) int d; fscanf(inputFile, "%d", &d) .

Your code has undefined behavior because you test while (ch != EOF) with ch uninitialized the first time. You should write:

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

Yet the problem is you read individual bytes instead of parsing the file contents for numbers expressed as decimal integers. You should use fscanf() to convert the text into integers.

You also forgot to close the file, causing resource leakage.

Here is a modified version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM