2.3) C Input and output functions
Input and output (I/O) functions are crucial for interacting with users and external devices in C programming.
They allow your programs to receive input from users and display output to the screen or other output devices.
In C, the standard library provides a set of I/O functions to facilitate these tasks.
Table of Contents
Standard Input/Output Library
The standard I/O library in C is provided by the <stdio.h>
header file. This library includes functions that enable you to read data from standard input (usually the keyboard) and write data to standard output (usually the screen).
Input Functions
C provides the following input functions for reading data from the user:
- scanf: Reads formatted data from standard input.
int age;
scanf("%d", &age); // Read an integer from the user
- getchar: Reads a single character from standard input.
char ch;
ch = getchar(); // Read a single character
Output Functions
C provides the following output functions for displaying data to the user:
- printf: Prints formatted data to standard output.
int x = 10;
printf("The value of x is %d\n", x); // Output: The value of x is 10
- putchar: Writes a single character to standard output.
char ch = 'A';
putchar(ch); // Output: A
Formatted Output
The printf function supports formatting options to control how data is displayed. Common format specifiers include:
%
d: Integer- %f: Floating-point number
- %c: Character
%
s: String
You can also use modifiers to control width, precision, and alignment. For example:
printf("Formatted output: %5d\n", 123); // Output: Formatted output: 123
printf("%.2f\n", 3.14159); // Output: 3.14
Formatted Input
The scanf function also supports format specifiers for reading data in specific formats. For example:
int num;
scanf("%d", &num); // Read an integer from the user
float price;
scanf("%f", &price); // Read a floating-point number from the user
Buffered I/O:
C I/O operations are typically buffered, meaning that data is read/written in chunks for efficiency. The fflush
function can be used to clear the buffer.
fflush(stdin); // Clear input buffer (not recommended on some systems)
fflush(stdout); // Clear output buffer
File I/O
Apart from standard I/O, C also provides functions for file input/output. These functions allow you to read from and write to files. Common file I/O functions include fopen
, fclose
, fprintf
, fscanf
, fputc
, fgetc
, etc.
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w"); // Open file for writing
if (file != NULL) {
fprintf(file, "Hello, File I/O!"); // Write to file
fclose(file); // Close the file
}
return 0;
}