Input and output (I/O) operations are essential aspects of C programming, allowing you to interact with users and handle data. In this article, we’ll delve into the basics of input and output operations in C, providing real-world examples and output demonstrations to help you understand and apply these concepts effectively. Understanding input and output operations is crucial for any C programmer. In this article, we’ve covered the basics of performing input and output operations, both for keyboard interactions (printf() and scanf()) and file operations (fprintf() and fscanf()).
Output Operations
Printing Text with printf()
The printf()
function is used to display text and data on the screen. You can format the output using format specifiers such as %d
, %f
, %c
, and %s
for integers, floats, characters, and strings, respectively.
#include <stdio.h>
int main() {
int age = 25;
float height = 5.9;
printf("My age is %d years, and my height is %.2f feet.\n", age, height);
return 0;
}
Output:
My age is 25 years, and my height is 5.90 feet.
Writing to Files with fprintf()
You can also use fprintf()
to write formatted text and data to files. This is especially useful for creating and manipulating data files.
#include <stdio.h>
int main() {
FILE *file;
file = fopen("output.txt", "w"); // Open the file for writing
if (file != NULL) {
fprintf(file, "Hello, world!\n");
fprintf(file, "This is a file created using C programming.\n");
fclose(file); // Close the file
} else {
printf("Unable to open the file.\n");
}
return 0;
}
Output (output.txt):
Hello, world!
This is a file created using C programming.
Input Operations
Reading from the Keyboard with scanf()
The scanf()
function is used to read data from the keyboard. You should specify format specifiers to match the data types you want to read.
#include <stdio.h>
int main() {
int age;
float height;
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your height (in feet): ");
scanf("%f", &height);
printf("You entered age: %d and height: %.2f feet.\n", age, height);
return 0;
}
Output (After User Input):
Enter your age: 25
Enter your height (in feet): 5.9
You entered age: 25 and height: 5.90 feet.
Reading from Files with fscanf()
Similarly, you can use fscanf()
to read formatted data from files. This is useful for processing data stored in files.
#include <stdio.h>
int main() {
FILE *file;
file = fopen("input.txt", "r"); // Open the file for reading
if (file != NULL) {
int num;
fscanf(file, "%d", &num);
printf("Read from file: %d\n", num);
fclose(file); // Close the file
} else {
printf("Unable to open the file.\n");
}
return 0;
}
Input File (input.txt):
42
Output:
Read from file: 42