Pranav Totla
Pranav Totla

Reputation: 2432

Wrong data display on stdout: C File Operation

I wrote the following code:

main()
{
    FILE *fp;
    fp=fopen("ftest.txt","r");
    char c, filestring[100];
    int i=0;
    while((c=getc(fp))!=EOF)
    {
        filestring[i]=c;
    }
    printf("str is %s",filestring);
    fclose(fp);
}

The file ftest.txt contains the words Hello World.

enter image description here

The output displayed is not correct, it is either some other font or some other encoding.

enter image description here

What is the reason for this? And how do I solve this problem?

At the same time, this code runs well (shows output on stdout in "English"):

 main()
    {
        FILE *fp;
        fp=fopen("ftest.txt","r");
        char c;
        while((c=getc(fp))!=EOF)
        {
            printf("%c",c);
        }
        fclose(fp);
    }

I need the first code to work, as I've to search in the text file. How to solve this?

The question is different from Output is not displying correctly in file operation as I'm able to "display" the correct output (as in second code), but I'm not able to write the contents of the file into a string.

Things I've tried:

1) Changing the mode in which the file is opened from "r" to "rb".

2) Changing the Notepad encoding to all available options: ANSI, UTF etc.

Upvotes: 0

Views: 112

Answers (2)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

... and there's also a third part that's wrong here:

getc() returns an int, you're assigning it to a char before comparing it with EOF, which is defined as -1. If it just so happens that getc returns character 255, it gets assigned to a char, a signed 8 bit value, which results in, in a manner of speaking (char)-1, which then gets signed-extended to -1.

Upvotes: 0

cjubb39
cjubb39

Reputation: 464

There are two parts of the answer:

  • You never increment i. This means you're just overwriting the same spot (the first space in the array) in the while loop. That's why the first value of the junk is a 'd' (the last character of your input).

  • The junk after the 'd' is because the array is never initialized, meaning that there is random junk already there that is never overwritten.

Another note: doing the first way would require manually adding a null byte \0 to the end of the array (either by initializing the whole thing to \0s or just after the last character is read in. This is so the string is read correctly by printf.

Upvotes: 1

Related Questions