Why does my fputc/fwrite keep printing in Hex and how do I print to the middle of a file?

StackOverflow https://stackoverflow.com/questions/23460971

  •  15-07-2023
  •  | 
  •  

Pregunta

I am trying to use fseek to go to a specific location in a file and print text. But when I use either fputc or fwrite they keep inputting Hex values instead of the char value. The file is a .dat and is filled with 0's initially. So in addition to this if I try to write somewhere the rest of the file is deleted.... I need it to stay the same but with this new text overwriting that particular location. In addition to this, why does my fseek move 2 bytes instead of 1 at a time? Code:

    FILE * pF;
pF = fopen( "/home/caleb/Documents/PA3/dssoo_p3_material_v2/disk.dat" , "wb" );
fseek (pF, 4, SEEK_SET);
char c='c';
fputc(c, pF);
//char buffer[] = { 'x' , 'y' , 'z' };
//fwrite (buffer , sizeof(char), sizeof(buffer), pF);
fclose (pF);

Notice that fwrite is commented out here. I have also tried different values other than wb in fopen. I get: 0000 0000 63

Is it required to be in Hex due to it being a .dat file? Every 0 here does represent a byte correct? If a char takes up a byte shouldn't it be able to take up one spot(assuming Hex isn't required)?

EDIT: I've realized that if I cat it prints out the character. But does this mean that every two spaces is considered a byte?

¿Fue útil?

Solución

0x64 = 'c' = 99 (decimal). The 'byte' value is the same, represented in different ways.

If looking at the content of a file using a debugger, the debugger may present the data to you in 'Hex'; in which case it would show a pair of Hex digits which represent one byte.

(Yes, 'in hex, every pair of characters is a byte.)

In C, you can print out a byte value represented in various ways:

printf("%d", 0x63);  // will print out: 99
printf("%X", 0x63);  // will print out: 63
printf("%c", 0x63);  // will print out: c

printf("%d", 99);  // will print out: 99
printf("%X", 99);  // will print out: 63
printf("%c", 99);  // will print out: c

printf("%d", 'c');  // will print out: 99
printf("%X", 'c');  // will print out: 63
printf("%c", 'c');  // will print out: c
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top