Input & Output in C Language (Functions & Operations With Example)
Input & Output in C Language (Functions & Operations With Example)
Share 2.56%
Table of Contents
Introduction
Input in C
Output in C
Input and Output Functions in C Programming
Input Functions in C
Output Functions in C
What is File Input/Output in C?
File Input Output in C (Functions to Handle Files)
Formatted and Unformatted Input/Output in C
Difference Between Formatted and Unformatted Input Output in C
Introduction
Input-output operations in C are essential for interacting with users and
handling data. These operations allow a program to take input from the user
or external files and display results.
Input in C
Input in C programming means gathering data from the user or external
sources for processing. The most common way is through the console,
where functions like scanf() are used for formatted input, and getchar()
reads a single character.
Additionally, data can be read from files using functions like fscanf() and
fgets().
Input Functions in C
Below is a detailed explanation of common input functions in C
programming:
1. scanf()
Reads formatted input from the user, such as integers, floats, and strings.
Example:
int num;
printf("Enter a number: ");
scanf("%d", &num); // Takes integer input
printf("You entered: %d\n", num);
2. getchar()
Reads a single character from the user.
Example:
char ch;
printf("Enter a character: ");
ch = getchar(); // Reads one character Quiz
printf("You entered: %c\n", ch);
3. gets()
Reads a string from the user, including spaces (deprecated due to safety
concerns).
Example:
char str[50];
printf("Enter a string: ");
gets(str); // Reads the entire string
printf("You entered: %s\n", str);
4. fscanf()
Reads formatted data from a file.
Example:
5. fgets()
Reads a line of text from a file or the console.
Example:
Output Functions in C
Below is the explanation of common output functions in C programming:
1. printf()
Prints formatted output to the console.
Example:
2. putchar()
Outputs a single character to the console.
Example:
char ch = 'A';
putchar(ch); // Outputs the character 'A'
printf("\n");
3. puts()
Outputs a string to the console with a newline at the end.
Example:
4. fprintf()
Writes formatted data to a file.
Example:
5. fputs()
Writes a string to a file.
Example:
Key Notes:
Input functions like scanf() and fgets() are used to take data from the
user or files.
Output functions like printf() and fprintf() are used to display or save
data.
Always use fopen() and fclose() when working with files to ensure
proper file handling.
2. fclose()
Closes an opened file to free resources.
3. fprintf()
Writes formatted data to a file.
4. fscanf()
Reads formatted data from a file.
FILE *file = fopen("example.txt", "r");
char str[50];
fscanf(file, "%s", str); // Read data
printf("File content: %s\n", str);
fclose(file);
Input - scanf()
- fscanf()
Output - printf()
- fprintf()
int age;
float salary;
printf("Enter your age and salary: ");