Perhaps the best piece of advice about using library functions is to use system header files whenever possible.
getchar()
returns an integer.#include <stdio.h>
main()
{
char c;
while ((c = getchar()) != EOF)
putchar(c);
}
The reason is that c
is declared as a character rather than as an integer. This means that it is impossible for c
to hold every possible character as well as EOF
.
FILE *fp;
fp = fopen(file, "r+");
Once this has been done, one would think it should be possible to intermix read and write operations freely. Unfortunately, because of efforts to maintain compatibility with programs written before this option became available, this is not so: an input options may never directly follow an output operation or vice versa without an intervening call to fseek()
FILE *fp;
struct record rec;
while (fread((char *)&rec, sizeof(rec), 1, fp) == 1) {
/* do something to rec */
if (rec must be re-written) {
fseek(fp, -(long) sizeof(rec), 1);
fwrite((char *) &rec, sizeof(rec), 1, fp);
fseek(fp, 0L, 1); /* do nothing, but needed */
}
}
과거에 이런 일이 있었다고 하네요... 인터레스팅...
#include <stdio.h>
main() {
int c;
char buf[BUFSIZ];
setbuf(stdout, buf);
while ((c = getchar()) != EOF)
putchar(c);
}
Unfortunately, this program is wrong, for a subtle reason. The call to setbuf()
asks the I/O library to use the buffer buf
to hold characters on their way to the trouble lies, ask when buf
is flushed for the last time. Answer: after the main program has finished, as part of the cleaning up that the library does before handling control back to the operationg system. But by the time, buf
has already been freed!
errno
for error detectionThus when calling a library function, it is essential to tset the value it returns for an error indication before examing errno to find the cause of the error:
call library function
if (error return)
examine errno
signal()
function Thus it is not safe for a signal handler function to call any such library function . Thus the only portable, reasonably safe thing a signal handler for an arithmatic error can do is to print a message and exit (by using either longjmp()
or exit()
)
The best defense against problems is to keep signal handlers as simple as possible and group them all together.
https://www.mythos-git.com/Cruzer-S/CTAP/-/tree/main/Chapter05
[Book] C Traps and Pitfalls (Andrew Koenig)
[Site] 네이버 영영, 영한사전