I/O in C
Chapter: Input and Output in C
Input and output (I/O) operations are essential in any program, as they allow interaction with the user or external devices. In C, I/O operations are handled using functions from the standard input/output library (<stdio.h>
). This chapter covers various methods for reading inputs and displaying outputs, ranging from simple console I/O to working with files.
1. Introduction to I/O in C
C provides three standard streams for input and output:
Standard Input (
stdin
): Used for reading input, typically from the keyboard.Standard Output (
stdout
): Used for displaying output, typically to the screen.Standard Error (
stderr
): Used for error messages or diagnostics.
The most commonly used I/O functions in C are:
printf
andscanf
for formatted I/O.putchar
andgetchar
for character-based I/O.puts
andgets
for string-based I/O.
2. Console Input and Output
2.1 Printing Output with printf
printf
The printf
function is used for formatted output.
Syntax:
printf("format string", arguments);
The format string contains text and format specifiers (e.g.,
%d
,%s
) to display variables.The arguments correspond to the format specifiers.
Example:
#include <stdio.h>
int main() {
int age = 25;
float height = 5.9;
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
return 0;
}
Output:
Age: 25
Height: 5.9
Common Format Specifiers:
%d
Integer
123
%f
Floating-point number
123.45
%c
Character
'A'
%s
String
"Hello"
%x
Hexadecimal
7b
(for 123
)
%o
Octal
173
(for 123
)
%%
Prints %
character
%
2.2 Reading Input with scanf
scanf
The scanf
function is used to read formatted input.
Syntax:
scanf("format string", &variable);
The format string specifies the data type of the input.
The
&
(address-of operator) is used to pass the memory address of the variable where the input will be stored.
Example:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
Output:
Enter a number: 42
You entered: 42
Notes on scanf
:
Multiple inputs can be read at once:
scanf("%d %f", &int_var, &float_var);
scanf
stops reading strings at spaces. Usefgets
for multi-word input.
2.3 Character Input and Output
For single-character I/O, use getchar
and putchar
.
getchar
: Reads a single character from the input.Example:
char ch = getchar();
putchar
: Prints a single character to the output.Example:
putchar('A');
Example Program:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: ");
putchar(ch);
printf("\n");
return 0;
}
Output:
Enter a character: G
You entered: G
2.4 String Input and Output
gets
: Reads an entire line, including spaces. Avoidgets
, as it can cause buffer overflows.fgets
(Preferred): Reads a line of text safely, including spaces.Example:
char str[50]; fgets(str, sizeof(str), stdin);
puts
: Prints a string followed by a newline.Example:
puts("Hello, World!");
Example Program:
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Hello, ");
puts(name);
return 0;
}
3. File Input and Output
File I/O allows reading from and writing to files. The <stdio.h>
library provides functions like fopen
, fprintf
, fscanf
, fclose
, etc.
3.1 Opening and Closing Files
Use fopen
to open a file:
FILE *file_pointer = fopen("filename", "mode");
Modes include:
"r"
: Read mode."w"
: Write mode (overwrites the file)."a"
: Append mode."r+"
: Read and write.
Use fclose
to close the file:
fclose(file_pointer);
3.2 Writing to a File
Use fprintf
or fputs
for writing data to a file.
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("output.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
fprintf(fp, "Hello, File!\n");
fclose(fp);
return 0;
}
3.3 Reading from a File
Use fscanf
or fgets
to read data from a file.
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("output.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
char buffer[100];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
return 0;
}
4. Formatted and Unformatted I/O
4.1 Formatted I/O
Formatted I/O functions, like printf
and scanf
, allow the use of format specifiers for structured data input and output.
4.2 Unformatted I/O
Unformatted I/O functions, like getchar
, putchar
, gets
, and puts
, deal directly with raw data.
5. Best Practices for I/O in C
Validate Inputs: Always check for valid inputs to prevent errors or undefined behavior.
Handle File Errors: Check file pointers for
NULL
afterfopen
.Use Safe Functions: Prefer
fgets
overgets
, as it avoids buffer overflows.Close Files: Always close files after reading or writing.
6. Sample Questions and Solutions
Question 1: Write a program to read and print a sentence using fgets
and puts
.
fgets
and puts
.Solution:
#include <stdio.h>
int main() {
char sentence[100];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);
printf("You entered: ");
puts(sentence);
return 0;
}
Question 2: Write a program to copy content from one file to another.
Solution:
#include <stdio.h>
int main() {
FILE *source, *destination;
char ch;
source = fopen("source.txt", "r");
if (source == NULL) {
printf("Error opening source file.\n");
return 1;
}
destination = fopen("destination.txt", "w");
if (destination == NULL) {
printf("Error opening destination file.\n");
fclose(source);
return 1;
}
while ((ch = fgetc(source)) != EOF) {
fputc(ch, destination);
}
fclose(source);
fclose(destination);
printf("File copied successfully.\n");
return 0;
}
Summary
Input and output operations are fundamental for creating interactive and file-based C programs. In this chapter, we covered console I/O using printf
, scanf
, getchar
, and putchar
, as well as file I/O with fopen
, fscanf
, and fprintf
. By understanding these concepts, you can create robust programs that interact with users and external files. Practice the sample questions to solidify your skills.
Last updated
Was this helpful?