stdio h in C

stdio-h-in-C.jpg

stdio.h (Standard Input Output header) is one of the most common and basic header files in the C programming language. It offers built-in functions and macros to execute input and output functions, which include displaying output on the screen, reading the keyboard for input, and file I/O. Functions such as printf(), scanf(), fopen(), fread(), and fwrite() are all included and part of this library. stdio.h is used every time you are interacting with users or working with files in a meaningful way, and it is essential in developing data-driven or interactive C programs.

Table of Contents:

What is <stdio.h> in C?

The <stdio.h> is a pre-built, standard library header in the C language. The acronym stdio stands for Standard Input and Output, which means it includes input/output functions. This header file contains variables, multiple functions, and multiple macros, which are related to the input and output operations in C.
Syntax

#include <stdio.h>

“#include” is a preprocessor directive in C. This directive is used to include a header file in a program.

Difference between <> and “” inclusion

Aspect <> “”
Purpose Includes standard/system header files Includes user-defined or local header files
Search Path Searches only in system directories Searches current directory first, then system dirs
Common Use Case For headers like stdio.h, stdlib.h, etc. For your own headers, like myheader.h
Example #include <stdio.h> #include “myfile.h”
Flexibility Less flexible (only system paths) More flexible (supports local development)
Compilation Behavior Minimal, which means standard headers are unique and reduces conflict for performance Higher, if local headers have the same name as system headers
Risk of Conflict The compiler looks in predefined system include paths The compiler looks in current folder first, then system paths
Advance Your Career with C
Learn from industry pros and build real-world projects.
quiz-icon

Why and When to Include <stdio.h> in C?

The <stdio.h> header file is used to provide access to a library of standard input/output functions.

Why include <stdio.h> in C?

Reasons to include <stdio.h> in C:

  1. Access to Standard I/O Functions – This header file declares various functions. Some of these functions are:
    • printf() – for printing formatted output to the screen.
    • scanf() – for reading formatted input from the screen.
    • getchar() – for single-character input.
    • putchar() – for single-character output.
      It also contains file-handling functions like fopen(), fclose(), fread(), and fwrite(). Suppose we do not include <stdio.h>, then the compiler will not be able to recognize these functions.
  2. Code Reusability and Efficiency – Instead of implementing the fundamental input/output operations, we can include <stdio.h>, which allows us to leverage pre-written, optimized functions, saving development time and ensuring consistent behavior.
  3. Portability – The functions that are declared in <stdio.h> are a part of the C language, ensuring that the programs are using them for consistent behavior across different compilers and operating systems.

When to Include <stdio.h> in C?

You will see when you should include <stdio.h> in the C program:

  1. Whenever performing console input/output functions
    When the program needs to display information to the user, like messages or results, or receive input from them, like user data, then we use the functions from <stdio.h>.
  2. When Handling Files
    If the program needs to read from or write to the files on the system, then the file-handling functions provided by <stdio.h> are essential.
  3. In Almost All C Programs
    The most commonly included header file in C programming is the <stdio.h>, which is used in every C program to perform input and output operations.

stdio.h Library Variables

There are three variables in the stdio.h library. They are:

Sl. No. Variable Name Variable Description
1. FILE It is a data object that is used to store information about the controlling streams.
2. size_t It is an unsigned integral data type, which is the return type of the sizeof operator.
3. fpos_t It is a data type that is used to represent any position in a file.

Important stdio.h Macros

A macro is a small piece of code. Some of the commonly used stdio.h library’s macros are:

Sl.No. Macro Name Macro Description
1. EOF EOF stands for End of File. It contains a negative integer, which indicates the end of a file.
2. NULL It represents a NULL pointer. A NULL pointer means that it is empty.
3. FOPEN_MAX The integer that is present in it represents the number of files that can be opened simultaneously.
4. FILENAME_MAX It contains a value that indicates the maximum number of bytes allowed for a filename.
5. L_tmpnam It stores a value that defines how long a temporary filename can be, in terms of characters or bytes.
6. BUFSIZ It contains an integer that specifies how much memory (in bytes) is used as a buffer by the setbuf function.
7. TMP_MAX It tells how many unique temporary filenames the tmpnam function can create.
8. stdin, stdout, stderr These macros refer to standard input, output, and error. Internally, they are pointers to FILE objects that handle data flow between the program and the system.
9. _IOFBF, _IOLBF, _IONBF These macros define how input and output are buffered: fully, by line, or not at all. They help set the buffering mode for file operations.
10. SEEK_END, SEEK_SET, SEEK_CUR These macros help identify different positions in a file, such as the beginning, current location, or end, when moving the file pointer.

stdio.h Library Functions

There are many stdio.h library functions in C, which are used to perform different input and output functions. The functions are:

Sl.No. Function Name Function Description
1.printfOutputs formatted data to the standard output (stdout).
2.scanfReads formatted input from the standard input (stdin).
3.fprintfOutputs formatted data to a specified stream.
4.fscanfReads formatted input from a specified stream.
5.vprintfOutputs formatted data to stdout using a va_list.
6.vscanfReads formatted input from stdin into a va_list.
7.sprintfWrites formatted data to a string.
8.sscanfReads formatted input from a string.
9.snprintfWrites formatted data to a string with a size limit.
10.vsnprintfWrites formatted data to a buffer using a va_list with size limit.
11.vsprintfWrites formatted data to a string using a va_list.
12.vsscanfReads formatted input from a string into a va_list.
13.vfprintfOutputs formatted data to a stream using a va_list.
14.vfscanfReads formatted input from a stream into a va_list.
15.tmpnamGenerates a unique temporary filename.
16.tmpfileCreates a temporary binary file opened for update.
17.renameRenames a file or directory.
18.removeDeletes a specified file.
19.fopenOpens a file and returns a pointer to it.
20.fcloseCloses an opened file.
21.fflushFlushes the output buffer of a stream.
22.setbufSets the buffer for a stream.
23.setvbufControls the buffering for a stream.
24.freopenReopens a stream with a new file or mode.
25.fgetcReads the next character from a stream.
26.fputcWrites a character to a stream.
27.fgetsReads a string from a stream.
28.fputsWrites a string to a stream.
29.getcReads a character from a stream (similar to fgetc).
30.getsReads a string from stdin (unsafe and deprecated).
31.getcharReads a character from stdin.
32.putcharWrites a character to stdout.
33.putcWrites a character to a stream (similar to fputc).
34.putsWrites a string to stdout followed by a newline.
35.ungetcPuts a character back into the input stream.
36.freadReads binary data from a stream into an array.
37.fwriteWrites binary data from an array to a stream.
38.rewindResets the position of a stream to the beginning.
39.fgetposGets the current file position of a stream.
40.fseekSets the file position of a stream.
41.fsetposSets the stream position using a previously obtained value.
42.ftellReturns the current position of the file stream.
43.ferrorChecks for an error in the stream.
44.feofChecks if the end-of-file indicator is set.
45.perrorPrints a system error message to stderr.
46.clearerrClears error and EOF indicators for a stream.

Here we have taken an example to understand a few commonly used stdio.h functions:

C

Output:

stdio.h library function

File Handling with stdio.h in C

The stdio.h in C plays a vital role in file management. It contains functions like fopen() for opening the files, fclose() for closing them, and fread() and fwrite() for binary file processing.

Given below is an example of binary file read and write operations:

C

Output:

function handling with stdio h

Get 100% Hike!

Master Most in Demand Skills Now!

Buffering and Performance Optimization Using <stdio.h>

Buffering saves the data first, which will save both write operations to disk, like input/output and speed it up.

For example:

C

Output:

buffering and performance optimization

Error Handling and Diagnostic Functions in <stdio.h>

Error management in C involves checking the return values of functions and using built-in mechanisms like perror(), ferror(), and errno to check and correct failures. There are some common tools for error diagnostics:

  1. perror(“messages”) – Based on the last failed library function, it prints an error message. For example,
    FILE *file = fopen("file.txt", "r");
    if (file == NULL) {
    perror("Error opening file");
    }
  2. errno (from <errno.h>) – The global variable set when an error occurs. We should use #include<stdio.h> along with errno.h and string.h.
    For example,
    #include <errno.h>
    #include <string.h>
    printf("Error: %sn", strerror(errno));
  3. ferror(FILE *stream) – It helps to return non-zero if an error occurs with a file stream.
    For example,
    if (ferror(file)) {
    printf("Error reading from file.n");
    }
  4. clearerr(FILE *stream) – It resets the error and EOF indicators for a stream.

Practical Examples of <stdio.h> Functions in C

The following examples demonstrate how to effectively use the functions provided by in real-world C programs. These code snippets help you understand core concepts such as standard input/output, file handling, and formatted data processing using functions like printf(), scanf(), fopen(), fclose(), and others.

1. Writing and Reading Data Using an Array (File-Like Behavior)

The example below mimics writing to and reading from a file by using an integer array as a buffer:

C

Output:

stimulate writing data

2. Checking fwrite/fread Return Values for Errors

In this code, we will see a simulation of the fread/fwrite functions to check the result for success or failure:

C

Output:

stimulate freadfwrite

3. Using feof() and ferror() for File Status Detection

In this code, we will see how the ferror() and feof() functions work:

C

Output:

stimulate ferror feof
Kickstart Your Coding Journey with C – 100% Free
Beginner-friendly. No cost. Start now.
quiz-icon

Conclusion

The header in C is a standard library that provides essential functions for performing input and output (I/O) operations, including reading from standard input, writing to standard output, and handling files. stdio.h is a very important header library because it allows access to the functions needed to manipulate and handle data in C at the lowest level. If the developer understands file handling, buffered input/output, and error handling related to I/O, it is easier to write high-level, safe, robust, and high-performance code.

Stdio h in C – FAQs

1. What are stdin, stdout, and stderr?

These are the standard input/output streams defined in stdio.h:
stdin- Standard Input
stdout – Standard output
stderr – Standard error

2. What is the difference between getc() and fgetc()?

The getc() can be implemented as a macro, whereas fgetc() is always a function.

3. Can I use stdio.h to handle binary files?

Yes, we can handle binary files using stdio.h functions like fread and fwrite.

4. Is gets() safe to use?

No, gets() is not safe, as it does not prevent buffer overflow. We should use fgets() instead.

5. What is the difference between fprintf() and printf()?

Printf() is used to write to standard outputs, whereas fprintf() is used to write to a specific stream.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner