0
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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Pig
  • 2,002
  • 5
  • 26
  • 42

3 Answers3

2

because '0' == 0x30

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

Billy Pilgrim
  • 1,842
  • 3
  • 22
  • 32
0

'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.

Abhineet
  • 5,320
  • 1
  • 25
  • 43
0

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

Abhineet
  • 5,320
  • 1
  • 25
  • 43
Zodoh
  • 100
  • 7