Write C program to open an existing file“My.TXT” and read its content and displayit.
Question
Write a C program to open an existing file "My.TXT" and read its content and display it.
Solution
Sure! Here is a step-by-step guide to writing a C program that opens an existing file "My.TXT", reads its content, and displays it:
- Include the necessary header files:
#include <stdio.h>
- Declare the main function:
int main() {
// Code goes here
return 0;
}
- Declare a file pointer variable to hold the reference to the file:
FILE *file;
- Open the file using the
fopen
function:
file = fopen("My.TXT", "r");
Note: The second argument "r" specifies that the file is opened in read mode.
- Check if the file was opened successfully:
if (file == NULL) {
printf("Failed to open the file.\n");
return 1;
}
- Read the content of the file using a loop:
char ch;
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
- Close the file using the
fclose
function:
fclose(file);
- Complete the main function and the program:
int main() {
FILE *file;
file = fopen("My.TXT", "r");
if (file == NULL) {
printf("Failed to open the file.\n");
return 1;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
fclose(file);
return 0;
}
That's it! This program will open the file "My.TXT", read its content, and display it on the console.
Similar Questions
Which of the following operations can be performed on the file "NOTES.TXT" using the below code?FILE *fp;fp = fopen("NOTES.TXT", "r+");
File Handling:●Write a program that reads a text file and prints the number of words in it
Write a function in python to read the content from a text file "poem.txt" line by line and display the same on screen. Solution
What does fp point to in the program ?#include<stdio.h>int main(){FILE *fp;fp=fopen("trial", "r");return 0;}
#Write a program to create a text file and print the lines starting with ‘T’ or ‘P’. (Both# uppercase and lowercase)
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.