top

Search

C Tutorial

.

UpGrad

C Tutorial

Stdio.h in C

C programming relies on header files to access predefined functions, macros, and variables. stdio.h is the widely used header file, which stands for standard input-output header. It serves as a vital component for input and output operations in C programs. 

What is Stdio.h in C?

Stdio.h is a standard library header file in C with a set of input and output functions, macros, and variables. It is essential for performing various input and output operations in C programs. 

Stdio.h Advantages

1. Simplicity: The stdio.h functions are easy to understand and use, and specifically simple for beginners to learn C programming.

2. Portability: The functions in stdio.h work across different platforms and operating systems to make code more portable.

3. Efficiency: The functions and macros in stdio.h are optimized for performance to write efficient code without worrying about low-level details.

4. Flexibility: stdio.h functions handle different input and output scenarios, it is a versatile alternative for different programming tasks.

5. Standardization: As part of the C standard library, stdio.h is widely supported and maintained by various compiler vendors, ensuring a consistent and reliable programming experience.

Syntax of #include in C

Header files included with the #include directives from the system or user specified.

  • Standard system files: These files have the declaration of functions and macro definitions common throughout C source files. These files are present in the C library and are not created by the user.

  • Files created by the user: These files are built by the user to eliminate duplication or proper code management.

Specify the preprocessor where to look for a suitable stdio h in c header file before using the #include directive.

1. #include

This method is used to include system Stdio h in c header file present in the predetermined path of the system directories.

#include <stdio.h>
void main() {
    // Your C code here
}

2. #include "filename"

 This method is used to include user-defined header files, located in the same directory as the source file.

#include "myheader.h"
void main() {
    // Your C program code here
}

Importance of Include Stdio in C

Including stdio.h in a program, a programmer can utilize various functions, such as printf() and scanf(), to perform input and output operations. 

If stdio.h  is not included in the beginning it leads to an error during compilation, as the compiler will not recognize the functions or macros used in the program.

Role of the stdio.h Header File in C

The stdio.h header file plays a vital role in input and output operations within a C program. It enables transmission between the program and the environment with a set of stdio.h functions and macros working with input and output streams. 

The common tasks enabled by stdio.h include reading data from a keyboard, writing data to a screen and working with files.

Stdio.h in C Example

Example 1: Basic input and output

#include <stdio.h>
int main() {
    int num;
    printf("Enter an int: ");
    scanf("%d", &num);
    printf("Entered: %d\n", num);
    return 0;
}

Output:

Enter an int: 41
Entered: 41

Explanation: Here, printf() is used to display a prompt from the user to enter an integer. 

Then, scanf() to read the user's input and store it in the num variable. 

And, printf() to display the entered number.

Example 2: Reading and writing to a file

#include <stdio.h>
int main() {
    FILE *file;
    int num;
    file = fopen("numbers.txt", "w");
    fprintf(file, "42\n");
    fclose(file);
    file = fopen("numbers.txt", "r");
    fscanf(file, "%d", &num);
    fclose(file);
    printf("The number in the file is: %d\n", num);
    return 0;
}

Output:

The number in the file is: 42

Explanation: 

Here, fopen() is used to open a file named "numbers.txt" in write mode ("w"). 

Then fprintf() to write the number to the file and fclose() to close it.

The file is opened again in read mode ("r") and fscanf() to read the number from the file into the num variable and close the file. 

Then printf() to display the number read from the file.

Example 3: File error handling 

#include <stdio.h>
int main() {
    FILE *file;
    file = fopen("non_existent_file.txt", "r");
    if (file == NULL) {
        perror("Error in opening file");
        return 1;
    }
    // File processing code in this section
    fclose(file);
    return 0;
}

Output:

Error in opening file: No such file or directory present

Explanation: Here, we test to open a non-existent file in read mode with fopen(). The function returns NULL if there is an error, so check the condition and use perror() to display an error message before passing a non-zero exit code.

Example 4: Reading a line from a file 

#include <stdio.h>
int main() {
    FILE *file;
    char line[100];
    file = fopen("example.txt", "r");
    fgets(line, sizeof(line), file);
    fclose(file);
    printf("The number one line of the file is: %s\n", line);
    return 0;
}

Output:

The number one line of the file is: This is an example.

 Example 5: Using stdin and stdout

#include <stdio.h>
int main() {
    char name[50];
    fprintf(stdout, "Enter the name: ");
    fgets(name, sizeof(name), stdin);
    fprintf(stdout, "Hey, %s", name);
    return 0;
}

Output:

Enter the name: Joeil John
Hey, Joeil John

Stdio.h in C Use

  • Perform input and output operations in C programs. 

  • Reading and writing data from/to the standard input and output devices (e.g., keyboard and screen)

  • Reading and writing data from/to files

  • Formatting data for input and output operations

  • Handling errors related to input and output operations

  • Manipulating file positions and buffers

Stdio.h Library Variables

The stdio.h header file defines several library variables:

1.FILE: A data object that stores information about how to control input/output streams.

2. size_t: An unsigned integral data type representing the output of the sizeof operator.

3. fpos_t: A data object representing any position within a file.

Stdio.h Library Macros

Stdio.h contains several library macros:

1. NULL: Represents a null pointer constant

2. EOF: A negative integer signifying the end of a file.

3. BUFSIZ: An integer representing the buffer size used by the setbuf function.

4. L_tmpnam: An integer indicating the maximum length of a character array that can hold the longest temporary filename generated by the tmpnam function.

5. FOPEN_MAX: indicates the maximum number of files opened concurrently by the system.

6. FILENAME_MAX: represents the maximum length of a character array holding the longest possible filename.

7. TMP_MAX: represents the maximum unique filenames the tmpnam function generates.

8. stdin, stdout, stderr: macros for standard input, standard output, and standard error. They are pointers to the FILE object.

9. _IOFBF, _IOLBF, _IONBF: macros for Input Output Fully Buffered, Line Buffered, and Unbuffered. They specify the mode for file buffering.

10. SEEK_END, SEEK_SET, SEEK_CUR: macros used to locate different file positions.

Stdio.h Library Functions

The stdio.h library has numerous functions for performing various input and output tasks.

1. printf(): Prints formatted output to the console.

2. scanf(): Reads formatted input from the console.

3. fgets(): Reads a string from a file stream.

4. fputs(): Writes a string to a file stream.

5. fgetc(): Reads a character from a file stream.

6. fputc(): Writes a character to a file stream.

7. fread(): Reads data from a file stream into a buffer.

8. fwrite(): Writes data from a buffer into a file stream.

9. ftell(): Reports the current file position indicator for a file stream.

10.fopen(): Opens a file and returns a pointer to a file stream.

11. fclose(): Closes a file stream.

12. fflush(): Flushes the output buffer of a file stream.

13. setbuf(): Sets the buffer for a file stream.

14. setvbuf(): Sets the buffering mode for a file stream.

15. setlocale() - sets the locale for formatted input/output functions 

16. fprintf(): Prints formatted output to a file stream.

17. fscanf(): Reads formatted input from a file stream.

18. tmpfile(): Creates a temporary file.

19. tmpnam(): Generates a unique temporary file name.

20. remove(): Deletes a file.

21. rename(): Renames a file.

22. freopen(): Reopens a file stream with a specified mode.

23. getchar(): Reads a character from the standard input.

24. putchar(): Writes a character to the standard output.

25. gets(): Reads a string from the standard input.

26. puts(): Writes a string to the standard output.

27. feof(): Checks if the end-of-file indicator is set for a file stream.

28. ferror(): Checks if the error indicator is set for a file stream.

29. clearerr(): Clears the error and end-of-file indicators for a file stream.

30. fseek() - sets the file position indicator to a location in a file stream.

31. ftell() - returns the current value of the file position indicator for a stream.

32. fgetc() - reads the next character from a stream.

33. vprintf() - prints formatted output with a variable argument list to stdout 

34. vfprintf() - writes formatted output with a variable argument list to a file

35. vsprintf() - writes formatted output with a variable argument list to a string 

36. vscanf() - reads formatted input with a variable argument list from stdin

37. vfscanf() - reads formatted input with a variable argument list from a file 

38. vsscanf() - reads formatted input with a variable argument list from a string

Conclusion

The stdio.h header file is an essential component of C programming with a comprehensive set of functions for input and output operations. By comprehending the stdio.h in c source code, functions, macros, variables and stdio.h in c use, programmers can efficiently perform the reading and writing of data, handling files and manage errors related tasks.

FAQs

1. How do you format output in C using stdio.h? 

The printf() function is used. You can use format specifiers such as %d, %f, and %s to display integers, floating-point numbers and strings respectively.

2. What is a file pointer and how do they work in stdio.h? 

A file pointer is a variable pointer. In stdio.h, you use file pointers to read and write data to files. The most used file pointer functions are fopen(), fclose(), fgets(), and fputs().

3. Can you read and write binary files using stdio.h? 

fread() and fwrite() functions are used to read and write binary files respectively. Use "rb" or "wb" as the method parameter when opening the file. 

Leave a Reply

Your email address will not be published. Required fields are marked *