Home > Enterprise >  why fgetc() doesn't work well in my program (c language)?
why fgetc() doesn't work well in my program (c language)?

Time:10-17

1, 2, 3   // a.txt

This program is for opening the file, counting the numbers and reading the first letter of txt file. When I tried debugging, digit_char = fgetc(fp); doesn't worked properly. digit_char was empty. I used dynamic allocation to save the numbers in the array. There was no warning but the answer was not what I wanted. (digit_char=1) enter image description here

    FILE* fp;
    char digit_char;
    int NUM=1;
    fp = fopen("a.txt", "r");
    char ch;
    do
    {
        ch = fgetc(fp);
        if (ch == ',')
        {
            NUM  ;
        }
    } while (ch != EOF);


    int* arr;
    arr = (int*)malloc(sizeof(int) * NUM);

    digit_char = fgetc(fp);     // error...?
    
    free(arr);
    fclose(fp);

======

The following code fgetc() works very well. 1is saved in digit_char

FILE* fp;
    char digit_char;
    int NUM=3;
    fp = fopen("a.txt", "r");


    int arr[3];

    digit_char = fgetc(fp);
    
    //free(arr);
    fclose(fp);
    return 0;

I don't know why the first program doesn't work well..

CodePudding user response:

Once you have reached EOF, you're really at the end of the file. There's nothing more to read.

You need to rewind to the beginning of the file before attempting to read again.

Or at least seek to an earlier position.


Note that it's not possible to rewind or seek in the standard input stream stdin. To continue reading from stdin even after the user pressed the "end-of-file" button sequence, you need to clear the "error".

  •  Tags:  
  • c
  • Related