Search code examples
cfilescanffeof

Reading text from a file using fscanf()


guys i want to read the text from my file and assign every character to a single element of the array

char A[1000];

FILE * fpointer;
fpointer=fopen("text.txt","r");

i=0;
while(!feof(fpointer))
{
    fscanf(fpointer,"%c",&A[i]);
    i=i+1;
}

fclose(fpointer);

for (i=0;i<100;i++)
{
    printf("%c",A[i]);
}

return 0;

but the problem is that the output is some weird symbols instead of the file's text which is "This is just a test".Why is that happening ?


Solution

  • Possible reasons include:

    1. fopen failed to open the specified file. Fix by checking the return value of fopen.
    2. See Why is “while ( !feof (file) )” always wrong?
    3. You always print 100 characters, but if the file contains less than 100 characters, you're in trouble because you print uninitialized locations of the array, leading to UB. Fix by printing everything starting from zero upto i.

    Corrected code snippet:

    int i = 0, j = 0;
    char A[1000];
    
    FILE* fpointer;
    fpointer = fopen("text.txt", "r");
    if(!fpointer)
    {
        fputs("fopen failed! Exiting...\n", stderr);
        exit(-1); /* Requires `stdlib.h` */
    }
    
    while(fscanf(fpointer, "%c", &A[i]) != EOF)
    {
        i = i + 1;
    }
    
    fclose(fpointer);
    for (j = 0; j < i; j++){
        printf("A[%d] = '%c'\n", j, A[j]);
    }