How is EOF used in C language?
In C language, EOF is a constant that represents the end-of-file marker. It is defined in the stdio.h header file.
Here is the usage of EOF:
- When reading files, the EOF constant can be used to detect if the file has reached the end.
int ch;
while ((ch = getchar()) != EOF) {
// 读取文件内容,直到文件末尾
}
- In file operations, the EOF constant can be used to determine if the file writing was successful.
int result;
// 写入文件操作
result = fprintf(file_ptr, "Hello, World!\n");
if (result == EOF) {
// 写入文件失败
}
It is important to note that the value of EOF may vary in different systems, but it is usually a negative integer, with a value of -1 in most cases.