Pig
Pig

Reputation: 2122

Why does my getc() always return 30 when input is 0 in C?

int main(void){
    char buffer[5] = {0};  
    int i;
    FILE *fp = fopen("haha.txt", "r");
    if (fp == NULL) {
    perror("Failed to open file \"mhaha\"");
    return EXIT_FAILURE;
    }
    for (i = 0; i < 5; i++) {
        int rc = getc(fp);
        if (rc == EOF) {
            fputs("An error occurred while reading the file.\n", stderr);
            return EXIT_FAILURE;
        }
    buffer[i] = rc;
    }
    fclose(fp);
    printf("The bytes read were... %x %x %x %x %x\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]);
    return EXIT_SUCCESS;
}

I put eight 0s in my haha.txt file, and when I run this code it always gives me :

The bytes read were... 30 30 30 30 30

Can someone tell me why?

Upvotes: 0

Views: 334

Answers (3)

Zodoh
Zodoh

Reputation: 100

In your printf you use %x and this print in hex. The char '0' is equal to 48 in decimal so 0x30 in hex.

To print 0 in char you need to use printf with %c

Upvotes: 0

Abhineet
Abhineet

Reputation: 5399

'0' that you have entered in your text file is interpreted as char and not as an int. Now, when you try to print that char in its hex (%x) value, the code just finds the equivalent of that char in hex and prints it.

So, your '0' = 0x30. You can also try giving 'A' in your text file and printing it as hex, you will be getting '41' because 'A' = 0x41. For your reference, the AsciiTable.

If you want to print out exactly what you have typed in your text file, then simply change your printf("The bytes read were... %x %x %x %x %x\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]);

To

printf("The bytes read were... %c %c %c %c %c\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]); 
/* %c will tell the compiler to print the chars as char and not as hex values. */

You might want to read Format Specifiers and MSDN Link.

Upvotes: 0

Billy Pilgrim
Billy Pilgrim

Reputation: 1852

because '0' == 0x30

The character '0' is the 0x30 (ascii).

Upvotes: 2

Related Questions