In the realm of C programming, the ability to handle input and output operations is fundamental. Efficient interaction with users and external data sources is achieved through a set of Input-Output (I/O) functions. This tutorial aims to demystify these functions, providing insights into how they facilitate the exchange of data between a C program and its environment.
Input and Output in C programming language are accomplished through library functions. C programming language has defined many library functions for input and output.
In C programming, scanf() and printf() functions are most commonly used standard library function for taking input form keyboard and printing output on screen respectively.
Here, when we are say Input that means feeding data into C program using the keyboard and output means printing data on screen.
C programming language treats all the I/O devices and files as stream of data. A C program reading data from keyboard is similar to reading data from a file similarly printing data on screen is similar to writing data on a file. Three streams gets automatically attached when a program starts execution.
Stream | File Pointer | I/O Device |
---|---|---|
Standard Input | stdin | Keyboard |
Standard Output | stdout | Screen |
Standard Error | stderr | Screen |
Standard Library Functions for Input & Output of a Character
Header file stdio.h provides two in-built functions for reading a character from keyboard and writing/printing a character on screen.
Function | Description |
---|---|
getchar() | Returns a character from stdin stream(keyboard). |
putchar() | Writes a character to stdout stream(screen). |
#include<stdio.h> int main(){ char c; printf("Enter a character\n"); /* Reading a character from keyboard */ c = getchar(); printf("You Entered \n"); /* Printing a character on screen */ putchar(c); return(0); }
Program Output
Enter a character J You Entered J
Standard Library Functions for Input & Output of Strings
Function | Description |
---|---|
gets() | Reads a line from stdin(keyboard) and stores it into given character array. |
puts() | Writes a string to stdout(screen) stream excluding null terminating character. |
C Program for Input and Output of a String
#include <stdio.h> int main(){ char string[50]; printf("Enter your name\n"); gets(string); printf("You name is : "); puts(string); return(0); }
Output
Enter your name Jack You name is : Jack
Standard Library Functions for Formatted Input & Output
The stdio.h Library function printf() and scanf() are used to print and read formatted data in a C program respectively. Function printf and scanf both can be used for Input and output of all in-built data types as well as user defined data types.
The printf() function is a workhorse for output in C. It allows you to display formatted data on the console. The syntax involves a format string followed by variables or values to be printed.
The scanf() function is used for reading input from the console. It requires format specifiers to interpret the input correctly.
Function | Description |
---|---|
printf() | Print formatted data to stdout(screen). |
scanf() | Writes a character to stdout stream(screen). |
C Program to shows the use of printf function
#include <stdio.h> int main(){ printf("Printing characters\n"); printf("%c %c %c %c\n\n", 'a', 'A', '#', '1'); printf("Printing integers\n"); printf("%d %ld %10d %010d\n\n", 2015, 2015L, 2015, 2015); printf("Printing floating point numbers\n"); printf("%f %5.2f %+.0e %E\n\n", 1.41412, 1.41412, 1.41412, 1.41412); printf("Printing string\n"); printf("%s\n\n", "TechCrashCourse"); printf("Printing radicals\n"); printf ("%d %x %o %#x %#o\n\n", 2105, 2015, 2015, 2015, 2015); return 0; }Output
Printing characters a A # 1 Printing integers 2015 2015 2015 0000002015 Printing floating point numbers 1.414120 1.41 +1e+000 1.414120E+000 Printing string TechCrashCourse Printing radicals 2105 7df 3737 0x7df 03737
C Program to shows the use of scanf function
#include <stdio.h> int main(){ int a, b, sum; printf("Enter to integers to add\n"); /* Taking formatted input from user using scanf */ scanf("%d %d", &a, &b); sum = a + b; /* Printing formatted output */ printf("%d + %d = %d", a, b, sum); return 0; }Output
Enter to integers to add 5 3 5 + 3 = 8
File Input and Output
- Opening and Closing Files : Using the fopen function to open files is essential for working with them. Remember to use fclose to close the file after you're done.
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "w"); if (file != NULL) { // File operations fclose(file); } else { perror("Error opening file"); } return 0; }
- Reading and Writing Characters : Functions like fgetc and fputc make it easy to read and write characters inserted into files.
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "w"); if (file != NULL) { fputc('A', file); fclose(file); } else { perror("Error opening file"); } return 0; }
- Reading and Writing Lines : Commonly used functions are fgets and fputs, which read and write lines in files.
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "w"); if (file != NULL) { fputs("Hello, File I/O!", file); fclose(file); } else { perror("Error opening file"); } return 0; }
- Binary File I/O : Data appropriate for sophisticated data structures can be read and written in its raw binary form using binary file I/O.
#include <stdio.h> struct Employee { char name[50]; int id; }; int main() { struct Employee emp = {"John Doe", 123}; FILE *file = fopen("employee.dat", "wb"); if (file != NULL) { fwrite(&emp, sizeof(struct Employee), 1, file); fclose(file); } else { perror("Error opening file"); } return 0; }
- Error Handling in File I/O : If you want your file operations to succeed, you must check for problems while working with files. This is where error handling in file I/O comes in.
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "w"); if (file != NULL) { // File operations fclose(file); } else { perror("Error opening file"); } return 0; }
- Buffered I/O : C uses buffering to optimize I/O operations. The fflush() function is used to flush the buffer.
#include <stdio.h> int main() { FILE *file; char str[] = "Hello, buffered I/O!"; // Writing to a file with buffering file = fopen("buffered.txt", "w"); fprintf(file, "%s", str); // Flush the buffer fflush(file); fclose(file); return 0; }
Formatted Input and Output
- fprintf and fscanf - File Formatted I/O : The fprintf and fscanf functions are used for formatted file input and output.
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "w"); if (file != NULL) { int num = 42; fprintf(file, "The answer is: %d", num); fclose(file); } else { perror("Error opening file"); } return 0; }
- sprintf and sscanf - String Formatted I/O : The sprintf and sscanf functions operate similarly to printf and scanf but direct their output to strings instead of the console.
#include <stdio.h> int main() { char buffer[50]; int num = 42; sprintf(buffer, "The answer is: %d", num); printf("%s\n", buffer); return 0; }
- Format Specifiers : Format specifiers define the type and format of the data being read or written. Common format specifiers include %d for integers, %f for floats, %s for strings, and %c for characters.
#include <stdio.h> int main() { int num; char str[50]; float f; scanf("%d %s %f", &num, str, &f); printf("Values entered: %d, %s, %f\n", num, str, f); return 0; }
Conclusion
Gaining expertise in input-output functionalities in C programming holds a key role in developing resilient and engaging applications. Whether you are showcasing data on the console, receiving user input, or managing files, a comprehensive grasp of these functions provides the capability to construct adaptable and effective programs.
As you delve deeper into these advanced topics, consider real-world scenarios where these techniques can significantly impact the design and performance of your programs. By mastering these advanced techniques, you'll be well-equipped to build sophisticated C programs that excel in both functionality and reliability. Continue your exploration and experimentation, and enjoy the journey of becoming a proficient C programmer.