Input and output (I/O) operations are fundamental in programming, enabling communication between a program and its environment. In the C programming language, various types of I/O functions and methods exist, each serving specific purposes. In this guide, we’ll explore the types of input and output in C, their usage, and examples.
Introduction to Input and Output in C
Standard Input and Output (stdio.h)
- Reads data from the standard input (usually the keyboard).
int num; scanf("%d", &num);
- Prints data to the standard output (usually the console).
int x = 10; printf("Value of x is %d", x);
File Input and Output (stdio.h)
Opening and Closing Files
fopen()to open a file and
fclose()to close it.
FILE *file; file = fopen("data.txt", "r"); // Open for reading fclose(file);
Reading from Files:
- Reads data from a file.
FILE *file; int num; file = fopen("data.txt", "r"); fscanf(file, "%d", &num);
Writing to Files:
- Writes data to a file.
FILE *file; int x = 20; file = fopen("output.txt", "w"); // Open for writing fprintf(file, "Value of x is %d", x);
Character Input and Output (conio.h)
- Reads a character from the keyboard without displaying it.
char ch; ch = getch();
- Displays a character on the console.
char ch = 'A'; putch(ch);
String Input and Output (string.h)
- Reads a string from the standard input.
char name; gets(name);
- Displays a string on the console.
char greeting = "Hello, World!"; puts(greeting);
Binary Input and Output
- Binary file operations (
fwrite()) enable reading and writing binary data directly.
- Useful for handling non-textual data like images, audio, or structured binary files.
Formatted Input and Output
- Format specifiers in
scanf()define the type and format of data.
int num = 42; printf("The answer is %d", num);
Error Handling in Input and Output
- Check return values of I/O functions for errors.
- Handle errors gracefully using conditional statements and error messages.
- Always close files after opening them.
- Validate user input to prevent unexpected behavior.
- Use appropriate I/O functions for the type of data you are working with.
Understanding the various types of input and output in C is essential for building robust and interactive programs. Whether you’re reading from the keyboard, files, or handling binary data, mastering I/O operations is a fundamental skill for C programmers.