C standard input output
Created By: chatGPT
C provides a rich set of functions for performing input and output operations through the stdio.h header file. This allows programs to read and write data to various streams like the keyboard and files.
#include <stdio.h>
int main() {
printf("Hello, World!\n"); // Output to console
return 0;
}
The printf function is used for formatted output. You can format your output using format specifiers. For example,
%d
is used for integers, %f
for floating-point numbers, and %s
for strings.int main() {
int age = 25;
printf("I am %d years old.\n", age);
return 0;
}
For input operations, the scanf function is utilized. It allows the program to read data from standard input, typically the keyboard. You need to specify the format of the expected input just like in printf.
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age); // Input from user
printf("You entered: %d\n", age);
return 0;
}
When dealing with strings, make sure to utilize character arrays properly, as scanf reads input until whitespace. For reading a full string, use fgets instead, as it can also handle spaces.
int main() {
char name[30];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Safely reads a string
printf("Hello, %s", name);
return 0;
}
File operations are also handled through the stdio.h functions. Use fopen to open a file, fprintf to write to it, fscanf to read from it, and fclose to close the file to free up resources.
int main() {
FILE *file;
file = fopen("example.txt", "w"); // Open file for writing
fprintf(file, "This is an example text.\n"); // Write to file
fclose(file); // Close the file
return 0;
}
Error handling is also a crucial aspect of input/output in C. Always check if the file was opened successfully before performing operations. Use the NULL comparison for this check.
int main() {
FILE *file;
file = fopen("nonexistent.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Perform operations if file opened successfully
fclose(file);
return 0;
}