C Input output
- Input Functions - scanf, getchar, getch
- Output Function - printf, pus , putchar
- File I/O - fopen, fclose, fread, fwrite, fprintf, and fscanf
Input Functions
Here are some of the functions
Function
Purpose
Example
scanf
Read input from standard input with format specifiers
scanf("%d", &num);
getchar
Read a single character from standard input
char ch = getchar();
getch
Read a single character without waiting for Enter
char ch = getch();
Example
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
char ch;
printf("Press a key: ");
ch = getch();
printf("You pressed: %c\n", ch);
char chr;
printf("Enter a character: ");
chr = getchar();
printf("You entered: %c\n", chr);
return 0;
}
Output Functions
Here are the Output functions used
Function
Purpose
Example
printf
Formatted output to the standard output (console)
printf("Hello World!");
puts
Outputs a string to the standard output
puts("This is a string.");
putchar
Outputs a character to the standard output
putchar('A');
Example
#include <stdio.h>
int main() {
int num = 42;
printf("The number is: %d\n", num);
char str[] = "Hello, C!";
puts(str);
char ch = 'A';
putchar(ch);
return 0;
}
File I/O
Here are the File I/O Functions
Function
Purpose
Example
fopen
Opens a file and returns a file pointer
FILE *file = fopen("example.txt", "w");
fclose
Closes a file
fclose(file);
fread
Reads a block of data from a file
fread(buffer, sizeof(char), 100, file);
fwrite
Writes a block of data to a file
fwrite(data, sizeof(int), 10, file);
fprintf
Formatted output to a file
fprintf(file, "Data: %d\n", data);
fscanf
Reads formatted data from a file
fscanf(file, "%s", str);
Example
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file != NULL) {
char buffer[100];
fscanf(file, "%s", buffer);
printf("Read from file: %s\n", buffer);
fclose(file);
}
return 0;
}
Error Handling
Example
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1; // Exit with an error code
}
// Continue with file operations
fclose(file);
return 0;
}