简体   繁体   中英

difference between the fgetc() and fgets()?

I am aware with the fact that fgetc() will read one character at a time from a file pointed by the FILE pointer which is used as argument.

fgets() will read the whole string upto the size specified in argument list but when end of line occurs fgetc() returns EOF while fgets() returns NULL .so why there are two confusing things to remember?

The reason one returns EOF while the other returns NULL is the difference in return types of the two functions: one returns an int , while the other returns a char* .

Both functions need to return a "special" value when the end of the input is reached. By "special" I mean a value that cannot appear in the input legally. For pointers, the special value in most cases is NULL , so that is what fgets returns. However, you cannot use NULL to mark the end of the input from fgetc , because character code of zero can legally appear in the input. That is why EOF is used as the "special value" in I/O functions that return a single character.

The answer is probably something along the lines of "We didn't know C would become quite so popular for quite so long."

Other mistakes in the C standard include creat() (no e, why?), strtok() (thread-unsafe by default!), sprintf() (unlikely you'll use it without a possible buffer overrun, else it is too big a hammer anyway), atoi() (almost impossible to probably check for errors), and more!

You'd have to ask the original designers of the C standard library of course, not sure if any of them are around.

In my view, many standard functions that accept a string buffer return that same buffer, so from that point of view fgets() ' behavior is totally regular and predictable.

If you're not afraid of NULL , the fact that it returns the pointer means the function can be chained:

char buf[128];
printf("you said '%s'\n", fgets(buf, sizeof buf, stdin));

The above is undefined if fgets() fails, but exchange printf() for something that has a well-defined handling of NULL and you see my point.

And it wouldn't make sense for fgetc() to return a pointer of course, since it's more low-level it just needs to return a single character or EOF , which int is the standard type for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM