easiest C Program to Write and Read a Character from a File
Question
easiest C Program to Write and Read a Character from a File
Solution
Sure, here is a step-by-step guide to writing and reading a character from a file:
- Include necessary headers: You need to include the standard input-output library.
#include <stdio.h>
- Define the main function: This is the entry point of the program.
int main() {
- Declare a file pointer: This will be used to handle the file operations.
FILE *file;
- Open the file for writing: Use
fopento open a file in write mode. If the file does not exist, it will be created.
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
- Write a character to the file: Use
fputcto write a single character to the file.
fputc('A', file);
- Close the file after writing: Always close the file to ensure data is properly saved.
fclose(file);
- Open the file for reading: Use
fopento open the file in read mode.
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
- Read a character from the file: Use
fgetcto read a single character from the file.
char ch = fgetc(file);
printf("Character read from file: %c\n", ch);
- Close the file after reading: Always close the file to free resources.
fclose(file);
return 0;
}
Putting it all together, the complete program looks like this:
#include <stdio.h>
int main() {
FILE *file;
// Open file for writing
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
// Write a character to the file
fputc('A', file);
// Close the file after writing
fclose(file);
// Open file for reading
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
// Read a character from the file
char ch = fgetc(file);
printf("Character read from file: %c\n", ch);
// Close the file after reading
fclose(file);
return 0;
}
This program writes the character 'A' to a file named "example.txt" and then reads it back, displaying the character on the screen.
Similar Questions
Write a C program to read a sentence and replace lowercase characters with uppercase and vice versa without using fgets function and without using the pointer
Which of the following correctly reads a string from a file in C?*1 pointfscanf(file, "%s", str)fprintf(file, "%s", str)fread(file, "%s", str)fput(file, "%s", str)
Explain how characters are stored and processed in C
Write C program to open an existing file“My.TXT” and read its content and displayit.
#include <stdio.h> #include <string.h> int main() { char *str = "hello, world"; char str1[9]; strncpy(str1, str, 9); printf("%s %d", str1, strlen(str1)); }
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.