Why does fgetc return integer
In C, return type of getchar , fgetc and getc is int not char. So it is recommended to assign the returned values of these functions to an integer type variable.
The return type is int to accommodate for the special value EOF, which indicates failure : If the standard input was at the end-of-file, the function returns EOF and sets the eof indicator feof of stdin. The fscanf function returns the number of fields that it successfully converted and assigned. The return value does not include fields that the fscanf function read but did not assign.
The return value is EOF if an input failure occurs before any conversion, or the number of input items assigned if successful. This function returns the number of characters read by the function. It returns the character present at position indicated by file pointer. After reading the character, the file pointer is advanced to next character. What is Fputs C? It is included in the C standard library header file stdio. The function fputs terminates after reaching terminating null character ''.
Please find below the description and syntax for each above file handling functions. What is fprintf in C? The fprintf function is used to write set of characters into file. It sends formatted output to a stream. What is end of file in C? Always store the return value of getchar fgetc , getc 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 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. The danger here is that with signed char s 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 on a particular implementation, which would cause spaces behave like EOF.
I don't use fancy compiler options. What am I missing? Having said that, two of the examples you gave don't actually do that. Good question. Here's a piece from machine. Check this great answer from the c-faq-site: Two failure modes are possible if, as in the fragment above, getchar's return value is assigned to a char.
Hope it helps! Edited: added the FatalError comment on this answer, this is explained on the c-faq site but this looks more clear to me "If you cast it to char then EOF takes the same value as some valid character and hence becomes indistinguishable from that character. Because the maximum length of an array is Integer. Only authorized users can answer the question. Please sign in first, or register a free account. Not the answer you're looking for?
Browse other questions tagged : c. Related Answers.
0コメント