Home  >  Article  >  Backend Development  >  How Do You Simulate EOF on Standard Input (stdin)?

How Do You Simulate EOF on Standard Input (stdin)?

DDD
DDDOriginal
2024-10-27 23:29:29705browse

How Do You Simulate EOF on Standard Input (stdin)?

Determining EOF of Standard Input Stream (stdin)

In programming, a common input source is the standard input stream (stdin), which reads input from the user's keyboard. However, determining when the user has finished inputting data and reached the end of the file (EOF) can sometimes be challenging.

Does stdin Have EOF?

By default, stdin does not inherently have an EOF. This means that a program reading from stdin will continue indefinitely, waiting for more input from the user.

Adding EOF to stdin

If you need to manually simulate an EOF on stdin, two common methods are:

  • Ctrl D (UNIX): In UNIX-based systems, pressing Ctrl D signals end of file.
  • Ctrl Z (Windows): In Windows OS, pressing Ctrl Z typically indicates the end of input.

Example:

The following code snippet uses fread to read from stdin and checks for EOF using Ctrl D:

<code class="c">#include <stdio.h>

int main() {
    char buffer[BUFSIZ];
    int c;
    
    while ((c = fread(buffer, sizeof(char), BUFSIZ, stdin)) > 0) {
        // Process input...
    }

    return 0;
}</code>

When the user presses Ctrl D, the fread() function will return -1, indicating the end of file. This triggers the end of the while loop.

Note:

It's important to note that the EOF simulation methods described above are system-dependent and may not work consistently across all platforms.

The above is the detailed content of How Do You Simulate EOF on Standard Input (stdin)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn