Welcome to our comprehensive guide on the C stdio.h Library! This tutorial is designed for both beginners and intermediate learners, so let's dive right in.
The stdio.h library is a fundamental part of the C programming standard library, providing functions for standard input/output operations. It allows us to interact with our keyboard (input) and screen (output).
printf() is a function used for outputting data to the standard output stream (screen). It takes a format string as an argument and optional additional arguments.
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}In the above example, printf("Hello, World!\n"); prints "Hello, World!" followed by a newline character (\n) to the screen.
scanf() is a function used for reading formatted data from the standard input stream (keyboard). It takes a format string and optional additional arguments.
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("You entered: %d\n", number);
return 0;
}In the above example, scanf("%d", &number); reads an integer from the keyboard and stores it in the number variable.
The format string used in printf() can include conversion specificators to format the output.
#include <stdio.h>
int main() {
int number = 123;
double floating_point = 123.456;
char character = 'A';
printf("Integer: %d\n", number);
printf("Floating-point: %.2f\n", floating_point);
printf("Character: %c\n", character);
return 0;
}In the above example, %d is used for integers, %.2f for floating-point numbers (with two decimal places), and %c for characters.
Which function is used for outputting data to the standard output stream?
When working with input/output functions, it's important to check for errors. The fprintf() function can be used for writing to a file, and fscanf() can be used for reading from a file.
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("Error: Unable to open file.\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fclose(file);
return 0;
}In the above example, we check if fopen() returns NULL, indicating an error. If an error occurs, we print an error message and return 1.
Remember, with great power comes great responsibility. Always be careful when working with files to avoid potential security issues.
We've covered the basics of the C stdio.h library, including printf() for outputting data, scanf() for inputting data, formatting output, and error handling. Keep practicing, and you'll be a C programming pro in no time! 🎉
Which function is used for writing to a file?