Course Content
C Tutorial
About Lesson

Input/Output (stdio.h)

C programming language relies on the standard input/output library, stdio.h, to handle input and output operations. These operations are essential for interacting with users, reading data from files, and displaying information on the screen. Let’s delve into the key aspects of Input/Output in C using stdio.h.

Basics of Input and Output in C

Printing Output with printf()

The printf() function is extensively used to display output on the screen. Its syntax involves formatting strings and placeholders. For instance:

#include <stdio.h>

int main() {
int num = 10;
printf("The value of num is: %dn", num);
return 0;
}

Reading Input with scanf()

The scanf() function facilitates the reading of input from the user or a file. It requires the use of format specifiers to interpret the input correctly. Here’s a basic example:

#include <stdio.h>

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %dn", num);
return 0;
}

File Input/Output Operations

Opening and Closing Files

stdio.h also handles file operations in C. To operate on files, you need to open them using fopen() and close them using fclose(). For instance:

#include <stdio.h>

int main() {
FILE *filePointer;
filePointer = fopen("example.txt", "w"); // Opens a file in write mode
fprintf(filePointer, "Hello, File Handling in C!"); // Writing to the file
fclose(filePointer); // Closing the file
return 0;
}

Reading from Files

Reading from a file involves using functions like fscanf() or fgets() to extract data. Here’s an example:

#include <stdio.h>

int main() {
FILE *filePointer;
char data[100];
filePointer = fopen("example.txt", "r"); // Opens a file in read mode
fscanf(filePointer, "%s", data); // Reads data from the file
printf("Data from file: %sn", data);
fclose(filePointer); // Closing the file
return 0;
}

Error Handling and EOF

In C programming, checking for errors and end-of-file (EOF) conditions is crucial when performing I/O operations. Functions like feof() and ferror() help in detecting these conditions to ensure robust code