Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getw return -1 when trying to read a character?

Tags:

c

I hoped I will see the result 65 since 65 is the ASCII value of A.

Why am I getting -1 instead?

#include <stdio.h>

int main()
{
    FILE *fp;
    fp=fopen("first.txt","w");
    putc('A',fp);
    fclose(fp);
    fp=fopen("first.txt","r");
    int x=getw(fp);
    printf("%d\n",x);

    return 0;
}
like image 995
play store Avatar asked May 11 '19 11:05

play store


2 Answers

You are writing one byte to the file, but then try to read sizeof(int) bytes back from it. getw() returns EOF because of that, and the value of EOF is -1.

For this reason, when using getw() you should examine the file handle using ferror() to be able to tell whether the value getw() returned is the value read from the file or an error code.

Or better yet, use fread() to read from files. getw() is an old function that's there for compatibility with old code. Or use getc() or fgetc() instead, which always return an unsigned char cast to an int and thus EOF can be easily distinguished:

int x = getc(fp);
if (x == EOF) {
    fputs("Error reading from file.\n", stderr);
} else {
    printf("%d\n",x);
}
like image 177
Nikos C. Avatar answered Oct 28 '22 03:10

Nikos C.


Oh, I see you have a problem right there with "w" just change "w" to "c" and smile. Actually, you're on the right track. Just change getw() to getc().

The output is -1 because you are using getw() function to read a .txt file that contains a char whereas, getw() function reads an integer from file. So the right function to use is getc() function because you have a char in your .txt file. getc() function reads character from file.

Copy and paste even faster:

#include <stdio.h>

int main()
{
    FILE *fp;
    fp=fopen("first.txt","w");
    putc('A',fp);
    fclose(fp);
    fp=fopen("first.txt","r");
    int x=getc(fp);
    printf("%d\n",x);

    return 0;
}

This would output 65.

like image 34
pasignature Avatar answered Oct 28 '22 02:10

pasignature