0

I know this is a stupid question but I don't understand this problem. Could anyone please explain to me?

I know that a char is 1 byte. I created a file sample.txt and fill in "1234" I used fseek and ftell to print the file size. The output is 4 bytes. This means each of char in the string "1234" is 1 byte.

But when I write like this printf("%d", sizeof('4')); The output is 4. So the char 4 is stored with 4 bytes.

So what are differences between the char 4 that read from the file and char 4 in the source?

*** My question was marked duplicated here: Why are C character literals ints instead of chars?

But it is not. The other topic doesn't explain why computer treats the char in the file as 1 byte each.

Louis Tran
  • 1,154
  • 1
  • 26
  • 46
  • This seems not a duplicate. The question you linked didn't answer why computer treat the char in the file with 1 byte. The answer said "More specifically the integral promotions. In K&R C it was virtually (?) impossible to use a character value without it being promoted to int first..." It didn't say why the chars in a file don't need to be promoted. – Louis Tran Oct 06 '18 at 04:22
  • 2
    Computer doesn’t treat chars in files as anything. It does what you tell it to do. A char is one byte by definition and a character literal is an int by definition, in C. If you write bytes to a file and read them as bytes, they’re bytes. That’s all you, not the computer. – Sami Kuhmonen Oct 06 '18 at 04:36
  • 1
    The problem is that although constants such as `'4'` are actually integer constants (in C; in C++, they are character constants — it is one of many reasons why C and C++ have to be treated as different languages). Granted, the value of a constant such as `'4'` is such that it fits into a `char` variable (and the basic character set — the alphabet, digits, punctuation, white space — must all be positive values), but that doesn't alter the fact that they're integer constants (type `int`). When used in a character string, they're truncated to 1 byte (usually 8 bits) each. – Jonathan Leffler Oct 06 '18 at 07:18
  • Read more about literals here: https://stackoverflow.com/questions/14111329/what-is-a-literal-in-c – Harshit Joshi Oct 06 '18 at 07:20
  • The characters inputted from the file are not literals. – Harshit Joshi Oct 06 '18 at 07:20

0 Answers0