Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 'fputc' use an INT as its parameter instead of CHAR?

Tags:

function

standard C lib:

int fputc(int c , FILE *stream);

And such behaviors occured many times, e.g:

    int putc(int c, FILE *stream);
    int putchar(int c);

why not use CHAR as it really is? If use INT is necessary, when should I use INT instead of CHAR?

like image 679
HaoCheng Avatar asked May 31 '10 13:05

HaoCheng


People also ask

Why does fputc take an int?

The fgetc function gets the next character converted to an int , and uses a special marker value EOF to indicate the end of the stream. To do that, they needed the wider int type since a char isn't quite large enough to hold all possible characters plus one more thing.

What is fputc () in C?

Description. The fputc() function converts c to an unsigned char and then writes c to the output stream at the current position and advances the file position appropriately. If the stream is opened with one of the append modes, the character is appended to the end of the stream.

How many arguments are required for the function fputc () in C language?

In line 7, a structure pointer variable fp of type struct FILE is declared. In line 8, fopen() function is called with two arguments namely "myfile.

What is use of fgetc () and fputc () functions?

The function fgetc() is used to read the character from the file. It returns the character pointed by file pointer, if successful otherwise, returns EOF. Here is the syntax of fgetc() in C language, int fgetc(FILE *stream)


1 Answers

Most likely (in my opinion, since much of the rationale behind early C is lost in the depths of time), it it was simply to mirror the types used in the fgetc type functions which must be able to return any real character plus the EOF special character. The fgetc function gets the next character converted to an int, and uses a special marker value EOF to indicate the end of the stream.

To do that, they needed the wider int type since a char isn't quite large enough to hold all possible characters plus one more thing.

And, since the developers of C seemed to prefer a rather minimalist approach to code, it makes sense that they would use the same type, to allow for code such as:

filecopy(ifp, ofp)
    FILE *ifp;
    FILE *ofp;
{
    int c;
    while ((c = fgetc (ifp)) != EOF)
        fputc (c, ofp);
}
like image 181
paxdiablo Avatar answered Oct 13 '22 22:10

paxdiablo