乐闻世界logo
搜索文章和话题

What is value of EOF and '\ 0 ' in C

1个答案

1

In C, EOF and '\0' are two distinct concepts, as detailed below:

  1. EOF:EOF is a macro defined in stdio.h, representing "End of File" (EOF), used to indicate that no more data can be read from the file stream. In most systems, EOF is defined as -1. It is commonly used in file reading functions such as fgetc and fscanf, which return EOF when reaching the end of the file or encountering an error.

    Example:

    c
    FILE *fp = fopen("example.txt", "r"); if (fp == NULL) { perror("file open failed"); return -1; } int ch; while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp);
  2. \0\0 is a null character, used in C to mark the end of a string. Its ASCII value is 0. Strings in C are typically stored as character arrays, with the end marked by \0, so the program knows when to stop processing the string.

    Example:

    c
    char str[] = "Hello, World!"; printf("%s\n", str); // normally prints the string // modify the character in the string to `\0` str[5] = `\0`; printf("%s\n", str); // only prints "Hello"

Both concepts are essential in C programming, serving different purposes in file operations and string handling.

2024年6月29日 12:07 回复

你的答案