简体   繁体   中英

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 ?

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

To expand on the points by @Cool Guy :

In case your files do not contain the null character , you can avoid using another variable to store the number of characters read. If you null terminate your read in characters, you can just print them directly as a string.

You have to make sure that A can hold enough characters. If you expect at most 1000 characters, make sure that A has a size of 1001 bytes to contain the terminating NUL character.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    char A[1001] = { 0 }; /* init to NUL, expect at most 1000 chars */
    int i;    
    FILE *fpointer;

    fpointer=fopen("text.txt","r");
    if(!fpointer) {
        perror("Error opening file"); /* print error message */
        exit(-1); /* Requires `stdlib.h` */
    }
    /* read all characters from fpointer into A */
    for (i=0; fscanf(fpointer, "%c", &A[i]) != EOF; i++);
    fclose(fpointer);

    printf("%s\n",A); /* print all characters as a string */

    /* alternatively, loop until NUL found */
    for (i=0; A[i]; i++)
        printf("%c", A[i]);
    printf("\n");

    return 0;
}

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