So I was writing a program on my Raspberry Pi Zero to count the frequencies of different word lengths in the input, but the program didn't stop at EOF.
So I tried this to debug:
#include <stdio.h>
#include <stdlib.h>
void main() {
char c;
while ( (c = getchar()) != EOF) {
putchar(c);
}
}
And compiled with this:
gcc test.c && ./a.out <input.txt
It printed out the input text, but then just kept printing question marks until I hit Ctrl+C. When I copied the program over onto my laptop and ran it there, everything worked fine.
I could just finish on the laptop, but I'm curious. Why can't the Pi detect when the file hit EOF?
First couple of facts:
The symbol EOF is a macro that expands to the integer constant -1. This integer constant will have the type int.
It's implementation-defined if char is signed or unsigned. The same compiler on different platforms might have different char implementations.
Now for the long explanation about your problem:
When integer types of different sizes are used in arithmetic expressions (and comparison is considered an arithmetic operator), then both operands of the expression undergoes usual arithmetic conversion to get a common type (usually int).
For smaller integer types, like for example char, that involves integer promotion to convert it to an int. For this promotion the value of the char needs to be kept intact, so e.g. -1 as a char will still be -1 as an int.
Because of how negative numbers are represented on most systems, the char value of -1 is (in hexadecimal) 0xff. For a signed char, when -1 is converted to an int, it keeps the value -1 (which will be represented as 0xffffffff for a 32-bit int type).
The problem comes when char is unsigned, because then when getchar returns EOF (the value -1) the unsigned char value will be equal to 255 (the unsigned decimal representation of 0xff). And when promoted to an int the value will still be 255. And 255 != -1!
That's why the getchar return type is int and not char. And one of the reason why all character-handling functions are using int instead of char.
So to solve your problem, you need to change the type of the variable c to int:
int c;
Then it will work
getchar returns int value not char value. Since you need some way to recognise in one getchar function if you read regular character or if function tells you there is nothing more to read - someone long time ago decided to use int so that some value bigger than char can be returned to indicate end of file. Change char to int.
getchar's return value is supposed to be able to return any ASCII (and extended ASCII) character between 0 and 255.
In order to make the distinction between an ascii and EOF, EOF cannot be a value in this interval, so getchar's return type must have more than 8 bits.
int getchar(void);
So you should write
int c;
while ( (c = getchar()) != EOF) ...
Related
I am trying to read a bitmap file, byte by byte, and I have a loop that runs until EOF is reached. To make that, I have a variable declared as unsigned int that stores each byte. The loop stops when this variable is equal to EOF.
The interesting point is: if I declare my variable as unsigned int it works. However, if I declare my variable as unsigned short int, the loop runs forever, because it never finds the EOF.
#include <stdio.h>
int main()
{
FILE *file;
unsigned int currentByte;
file = fopen("/home/stanley/Desktop/x.bmp", "rb");
while ((currentByte = fgetc(file)) != EOF) {
printf("%d \n", currentByte);
}
fclose(file);
return 0;
}
The code above is the code I am writing. If the file has a size of 90B, 90 bytes are printed on the screen.
However, for some reason, when I change it to unsigned short int currentByte, the loop keeps running forever. It is as if currentByte was never equal to EOF.
I read somewhere that EOF contains a negative value (-1). But if EOF is negative, why does it work when I use only unsigned int and why does it bug when I use unsigned short int? In theory, shouldn't the problem be related to the unsigned itself rather than the short? It's unsigned who can't store negative values.
I'm sorry if this is a very silly question. I'm trying to understand better how bits and bytes work, and some concepts might be strange to me yet.
I'm compiling it on the following environment:
OS: Ubuntu 18.04 x64
GCC: gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
Thanks in advance. :)
If the size of int is greater than the size of short, then you will encounter this problem.
Let's assume that EOF is of type int and contains the value -1. For the sake of example, let's also assume that int is a 32-bit value, while short is a 16-bit value.
In this case, if fgetc returns EOF, it will have a value of 0xFFFFFFFF when taken as an unsigned int. When comparing it to EOF (type int), the signed integer -1 will be converted to the unsigned value 0xFFFFFFFF. These two values are equal, so the comparison works as expected.
However, an EOF returned by fgetc, taken as an unsigned short, will have a value of 0xFFFF. Because the size of unsigned short is smaller than the size of int, when comparing this value to EOF, the unsigned short 0xFFFF will be converted to an int with a value of 0x0000FFFF (extra digits shown for clarity). Since -1 is not equal to 0xFFFF for a 32-bit value, this comparison is always not equal, and the loop will not stop.
The fact that fgetc returns int hints that you should keep it as that type, as you'll otherwise discard some information or cause confusion in comparisons.
You should use the type int to match what fgetc returns, not unsigned int. The reason the loop stop condition works with unsigned int is not that the value is ever negative, but that, when the != operator is used with unsigned and signed operands of the same rank, both get promoted to unsigned before the comparison. Assigning the EOF result of fgetc to currentByte and promoting EOF to unsigned both produce the same result, and thus they compare equal.
When you convert a signed integer to an unsigned integer (which happens when EOF is assigned to an unsigned integer variable), the result is converted to an unsigned integer by adding UINT_MAX + 1. So if EOF is -1, this value becomes UINT_MAX.
And UINT_MAX can properly fit only into unsigned int and not unsigned short.
And the result of this particular conversion is implementation defined and so the behavior of the program will depend on it.
Note the fgetc function returns a int, so you must use an int variable to store its value.
I am trying to learn C on my own and I'm kind of confused with getchar and putchar:
1
#include <stdio.h>
int main(void)
{
char c;
printf("Enter characters : ");
while((c = getchar()) != EOF){
putchar(c);
}
return 0;
}
2
#include <stdio.h>
int main(void)
{
int c;
printf("Enter characters : ");
while((c = getchar()) != EOF){
putchar(c);
}
return 0;
}
The C library function int putchar(int c) writes a character (an unsigned char) specified by the argument char to stdout.
The C library function int getchar(void) gets a character (an unsigned char) from stdin. This is equivalent to getc with stdin as its argument.
Does it mean putchar() accepts both int and char or either of them and for getchar() should we use an int or char?
TL;DR:
char c; c = getchar(); is wrong, broken and buggy.
int c; c = getchar(); is correct.
This applies to getc and fgetc as well, if not even more so, because one would often read until the end of the file.
Always store the return value of getchar (fgetc, getc...) (and putchar) initially into a variable of type int.
The argument to putchar can be any of int, char, signed char or unsigned char; its type doesn't matter, and all of them work the same, even though one might result in positive and other in negative integers being passed for characters above and including \200 (128).
The reason why you must use int to store the return value of both getchar and putchar is that when the end-of-file condition is reached (or an I/O error occurs), both of them return the value of the macro EOF which is a negative integer constant, (usually -1).
For getchar, if the return value is not EOF, it is the read unsigned char zero-extended to an int. That is, assuming 8-bit characters, the values returned can be 0...255 or the value of the macro EOF; again assuming 8-bit char, there is no way to squeeze these 257 distinct values into 256 so that each of them could be identified uniquely.
Now, if you stored it into char instead, the effect would depend on whether the character type is signed or unsigned by default! This varies from compiler to compiler, architecture to architecture. If char is signed and assuming EOF is defined as -1, then both EOF and character '\377' on input would compare equal to EOF; they'd be sign-extended to (int)-1.
On the other hand, if char is unsigned (as it is by default on ARM processors, including Raspberry PI systems; and seems to be true for AIX too), there is no value that could be stored in c that would compare equal to -1; including EOF; instead of breaking out on EOF, your code would output a single \377 character.
The danger here is that with signed chars the code seems to be working correctly even though it is still horribly broken - one of the legal input values is interpreted as EOF. Furthermore, C89, C99, C11 does not mandate a value for EOF; it only says that EOF is a negative integer constant; thus instead of -1 it could as well be say -224 on a particular implementation, which would cause spaces behave like EOF.
gcc has the switch -funsigned-char which can be used to make the char unsigned on those platforms where it defaults to signed:
% cat test.c
#include <stdio.h>
int main(void)
{
char c;
printf("Enter characters : ");
while ((c = getchar()) != EOF){
putchar(c);
}
return 0;
}
Now we run it with signed char:
% gcc test.c && ./a.out
Enter characters : sfdasadfdsaf
sfdasadfdsaf
^D
%
Seems to be working right. But with unsigned char:
% gcc test.c -funsigned-char && ./a.out
Enter characters : Hello world
Hello world
���������������������������^C
%
That is, I tried to press Ctrl-D there many times but a � was printed for each EOF instead of breaking the loop.
Now, again, for the signed char case, it cannot distinguish between char 255 and EOF on Linux, breaking it for binary data and such:
% gcc test.c && echo -e 'Hello world\0377And some more' | ./a.out
Enter characters : Hello world
%
Only the first part up to the \0377 escape was written to stdout.
Beware that comparisons between character constants and an int containing the unsigned character value might not work as expected (e.g. the character constant 'ä' in ISO 8859-1 would mean the signed value -28. So assuming that you write code that would read input until 'ä' in ISO 8859-1 codepage, you'd do
int c;
while ((c = getchar()) != EOF){
if (c == (unsigned char)'ä') {
/* ... */
}
}
Due to integer promotion, all char values fit into an int, and are automatically promoted on function calls, thus you can give any of int, char, signed char or unsigned char to putchar as an argument (not to store its return value), and it would work as expected.
The actual value passed in the integer might be positive or even negative; for example the character constant \377 would be negative on a 8-bit-char system where char is signed; however putchar (or fputc actually) will convert the value to an unsigned char. C11 7.21.7.3p2:
2 The fputc function writes the character specified by c (converted to an unsigned char) to the output stream pointed to by stream [...]
(emphasis mine)
I.e. the fputc will be guaranteed to convert the given c as if by (unsigned char)c
Always use int to save character from getchar() as EOF constant is of int type. If you use char then the comparison against EOF is not correct.
You can safely pass char to putchar() though as it will be promoted to int automatically.
Note:
Technically using char will work in most cases, but then you can't have 0xFF character as they will be interpreted as EOF due to type conversion. To cover all cases always use int. As #Ilja put it -- int is needed to represent all 256 possible character values and the EOF, which is 257 possible values in total, which cannot be stored in char type.
We often use fgetc like this:
int c;
while ((c = fgetc(file)) != EOF)
{
// do stuff
}
Theoretically, if a byte in the file has the value of EOF, this code is buggy - it will break the loop early and fail to process the whole file. Is this situation possible?
As far as I understand, fgetc internally casts a byte read from the file to unsigned char and then to int, and returns it. This will work if the range of int is greater than that of unsigned char.
What happens if it's not (probably then sizeof(int)=1)?
Will fgetc read a legitimate data equal to EOF from a file sometimes?
Will it alter the data it read from the file to avoid the single value EOF?
Will fgetc be an unimplemented function?
Will EOF be of another type, like long?
I could make my code fool-proof by an extra check:
int c;
for (;;)
{
c = fgetc(file);
if (feof(file))
break;
// do stuff
}
It is necessary if I want maximum portability?
Yes, c = fgetc(file); if (feof(file)) does work for maximum portability. It works in general and also when the unsigned char and int have the same number of unique values. This occurs on rare platforms with char, signed char, unsigned char, short, unsigned short, int, unsigned all using the same bit width and width of range.
Note that feof(file)) is insufficient. Code should also check for ferror(file).
int c;
for (;;)
{
c = fgetc(file);
if (c == EOF) {
if (feof(file)) break;
if (ferror(file)) break;
}
// do stuff
}
The C specification says that int must be able to hold values from -32767 to 32767 at a minimum. Any platform with a smaller int is nonstandard.
The C specification also says that EOF is a negative int constant and that fgetc returns "an unsigned char converted to an int" in the event of a successful read. Since unsigned char can't have a negative value, the value of EOF can be distinguished from anything read from the stream.*
*See below for a loophole case in which this fails to hold.
Relevant standard text (from C99):
§5.2.4.2.1 Sizes of integer types <limits.h>:
[The] implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.
[...]
minimum value for an object of type int
INT_MIN -32767
maximum value for an object of type int
INT_MAX +32767
§7.19.1 <stdio.h> - Introduction
EOF ... expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream
§7.19.7.1 The fgets function
If the end-of-file indicator for the input stream pointed to by stream is not set and a next character is present, the fgetc function obtains that character as an unsigned char converted to an int and advances the associated file position indicator for the stream (if defined)
If UCHAR_MAX ≤ INT_MAX, there is no problem: all unsigned char values will be converted to non-negative integers, so they will be distinct from EOF.
Now, there is a funny sort of loophole here: if a system has UCHAR_MAX > INT_MAX, then a system is legally allowed to convert values greater than INT_MAX to negative integers (per §6.3.1.3, the result of converting a value to a signed type that cannot represent that value is implementation defined), making it possible for a character read from a stream to be converted to EOF.
Systems with CHAR_BIT > 8 do exist (e.g. the TI C4x DSP, which apparently uses 32-bit bytes), although I'm not sure if they are broken with respect to EOF and stream functions.
NOTE: chux's answer is the correct one in the most general case. I'm leaving this answer up because I believe both the answer and the discussion in the comments are valuable in understanding the (rare) situations in which chux's approach is necessary.
EOF is guaranteed to have a negative value (C99 7.19.1), and as you mentioned, fgetc reads its input as an unsigned char before converting to int. So those by themselves guarantee that EOF can't be read from a file.
As for your specific questions:
fgetc can't read a legitimate datum equal to EOF. In the file, there's no such thing as signed or unsigned; it's just bit sequences. It's C that interprets 1000 1111 differently depending on whether it's being treated as signed or unsigned. fgetc is required to treat it as unsigned, so negative numbers (other than EOF) cannot be returned.
Addendum: It can't read EOF for the unsigned char part, but when it converts the unsigned char to an int, if the int is not capable of representing all values of the unsigned char, then the behavior is implementation-defined (6.3.1.3).
fgetc is required by the standard for hosted implementations, but freestanding implementations are permitted to omit most of the standard library functions (some are apparently required, but I couldn't find the list.)
EOF won't require a long, since fgetc needs to be able to return it and fgetc returns an int.
As far as altering the data goes, it can't change the value exactly, but since fgetc is specified to read "characters" from the file as opposed to chars, it could potentially read in 8-bits at a time even if the system otherwise defines CHAR_BIT to be 16 (which is the minimum value it could have if sizeof(int) == 1, since INT_MIN <= -32767 and INT_MAX >= 32767 are required by 5.2.4.2). In that case, the input character would be converted to a unsigned char that just always had its high bits 0. Then it could make the conversion to int without losing precision. (In practice, this just won't come up, since machines don't generally have 16-bit bytes)
I'm new to C. From the book there is a sample code:
#include <stdio.h>
main() {
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
The author writes a sentence like this:
We can't use char since c must be big enough to hold EOF in addition to any possible char. Therefore we use int.
Trying to understand, I modified the code like this:
#include <stdio.h>
main() {
char c=getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
if (c == EOF) {
putchar('*');
}
}
When I press Ctrl+D, * was printed, which means c holds EOF, which confuses me. Can anybody explain a little bit about this?
Because EOF is a special sentinel value (implementation defined, but usually -1 as an int type), it can't be distinguished from the value 255 if stored in a char variable. You need a type larger than 8 bits in order to represent all possibly byte values returned by getchar(), plus the special sentinel value EOF. There are 257 different possible return values from getchar().
Also, on a related note, character literals in C like 'a' have the type int. In C++, on the other hand, character literals have the type char. So you will see characters usually passed to and returned from C Standard Library functions as int types.
When you press CTRL-D, getchar() returns a value that doesn't fit in char. So char takes as much of it as it can. Let's assume a common number for EOF: 0xFFFFFFFF, in other words, -1. When this value is assigned to char (assuming it's signed), it will get a truncated value out of it, 0xFF, which is also -1.
So your if becomes:
if ((char)-1 == (int)-1)
the (char)-1 gets promoted to int to be able to compare it with (int)-1. Since on promotion of signed values, they get sign extended (to keep the original signed value), you end up comparing -1 and -1 which is true.
That said, this is only lucky. If you actually read a character with value 0xFF, you would mistake it with EOF. Not to mention EOF may not be -1 in the first place. All of this aside, you shouldn't let your program truncate a value when assigning to a variable (unless you know what you are doing).
char is, at least on your system, signed. Therefore, it can hold values from -128 to 127.
EOF is -1 and is, therefore, one of them.
You code works, as the -1 is retained. But as soon as you input the character which is equivalent to 255, you get erroneously -1 as well.
The type char is an unsigned 8-bit value (actually I think it can be 7 bits for the standard ASCII table, but I have never seen it implemented like that).
EOF is implementation defined, but often -1. That is a signed number (0xFFFFFFFF in a 32 bit machine). Most compilers will probably truncate that to 0xFF to compare to a char, but that's also a valid (but rarely used) character, so you can't really be sure if you have hex value 255 or EOF (-1).
In addition, some code may be written to look for a return value of <0 to stop reading. Obviously a char will never be less than zero.
The result of your getchar() is being stored as achar after performing a conversion by-value. The value in this case, is EOF likely (-1).
6.3.1.3-p1 Signed and unsigned integers
When a value with integer type is converted to another integer type
other than _Bool, if the value can be represented by the new type, it
is unchanged.
This is also accounted for during value comparison in your while-condition through value comparison via conversion:
6.5.9-p4 Equality Operators
If both of the operands have arithmetic type, the usual arithmetic conversions are performed. Values of complex types are equal if and
only if both their real parts are equal and also their imaginary parts
are equal. Any two values of arithmetic types from different type
domains are equal if and only if the results of their conversions to
the (complex) result type determined by the usual arithmetic
conversions are equal.
Both char and int are integer types. Both can hold the integer-value (-1) on your platform. Therefore your code "works".
K&R provide this getchar() example:
int getchar(void)
{
char c;
return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF;
}
c is cast to unsigned char here to avoid sign extension issues, but in the fputs() example...
int fputs(char *s, FILE *iop)
{
int c;
while (c = *s++)
putc(c, iop);
return ferror(iop) ? EOF : 0;
}
*s is assigned to an int without first casting to an unsigned char. Why is the cast unnecessary this time?
It is not about "sign extension issues". This implementation of getchar makes sure that all successfully read characters are returned as non-negative int values. This behavior is required by the specification of getchar, which literally says that the character read is returned as unsigned char values converted to int, even if char is signed on the given platform. What you see there is basically a direct implementation of getchar spec.
Meanwhile fputs does not return any specific character values. fputs does not return c to the user. That c is a purely internal variable. It should preserve the original value of char type on the given platform, since the value of c is then passed to putc. putc does not expect character values converted to non-negative range, it expects original character values, which could easily be negative if char is signed.
BTW, why did you look at fputs, and not fputc? If you look at fputc, which just like getchar returns a character value, you will probably see that it is implemented similarly to getchar in that regard.
I completely misunderstood the question the first time around. The problem here is that getchar() needs to return either a char in the entire range 0-255 or EOF. On most platforms EOF = -1. In order to return both a negative value and a char, int must be used.
This is not the case in fputs. In this example, a char is being assigned to an int in the while loop. "Lower" types are promoted to "higher" types. From page 44 KR, The C Programming Language:
If either operand is a long double, convert the other to a long double.
Otherwise, if either operand is a double, convert the other to a double.
Otherwise, if either operand is a float, convert the other to a float.
Otherwise, convert char and short to int
Then, if either operand is a long, convert the other to long.
According to the man page,
The fputc() function writes the character c (converted to an unsigned char) to the output stream pointed to by stream.
The cast is specifically performed for you inside the function.
Aside from that, assigning from char to negative int and back to char is guaranteed to produce the correct result, and char to negative int to unsigned char is guaranteed to have the same result as a direct cast from char to unsigned char. Other cases may produce signed integer overflow, which produces undefined behavior (i.e., could crash). But most platforms handle that by quiet binary truncation, in such a way that many programmers never worry about it at all.