Skip to main content

Standard Files in C

Standard Files

In C, there are three standard files that are automatically opened for a program when it starts running.

These standard files are:

  • stdin: This is the standard input file. It is usually connected to the keyboard or another input device, and is used to read input data from the user or from another program.

  • stdout: This is the standard output file. It is usually connected to the console or terminal window, and is used to write output data to the screen or to another program.

  • stderr: This is the standard error file. It is also usually connected to the console or terminal window, and is used to write error messages and other diagnostic information to the screen or to a log file.

  • These three files are automatically opened by the operating system when a program starts running, and can be accessed using the file pointers stdin, stdout, and stderr.

For example:

  • To read input data from the user, you can use the scanf() function with the stdin file pointer as its input source.
  • Similarly, to write output to the screen, you can use the printf() function with the stdout file pointer as its output destination.
  • Finally, to write error messages to the screen, you can use the fprintf() function with the stderr file pointer as its output destination.

Example

#include <stdio.h>

int main() {
char buffer[50];

// Read input from stdin
printf("Enter a string: ");
fgets(buffer, 50, stdin);

// Write output to stdout
printf("You entered: %s", buffer);

// Write error message to stderr
fprintf(stderr, "This is an error message.\n");

return 0;
}

Explanation:

  • We first declare a character array buffer with a size of 50. We then use fgets() to read a string of up to 50 characters from stdin, and store it in buffer.
  • We then use printf() to write a message to stdout that includes the input string we just read from stdin.
  • Finally, we use fprintf() to write an error message to stderr.
  • When this program is run, the user is prompted to enter a string. Once they do, the program writes the input string to stdout, and also writes an error message to stderr.

Output:

Enter a string: Hello, World!
You entered: Hello, World!

This is an error message.