Write C program to open an existing file“My.TXT” and read its content and displayit.
Question
Write C program to open an existing file“My.TXT” and read its content and displayit.
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
fopenfunction:
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
fclosefunction:
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
Write a program in C to append lines at the end of a text file.File Name: input1.txtInput format :The input consists of the contents to be appended in the given file.Output format :The output displays the contents in the file after appending user input.Sample test cases :Input 1 :welcome to C programmingOutput 1 :Coding challenges are tests
easiest C Program to Write and Read a Character from a File
Which of the following operations can be performed on the file "NOTES.TXT" using the below code? FILE *fp; fp = fopen("NOTES.TXT", "r+"); ans. Writing Read and Write Appending Reading
What will be the output of the following code? #include <stdio.h> int main() { FILE *file = fopen("test.txt", "w"); fputs("Line 1\nLine 2", file); fclose(file); file = fopen("test.txt", "r"); char buffer[50]; while (fgets(buffer, sizeof(buffer), file)) { printf("%s", buffer); } fclose(file); return 0; }Question 4AnswerA.Line 1 Line 2B.Line 1Line 2C.Compilation errorD.Runtime error
What should be in the Missing Line in the following C Code for it to display the code of itself.#include<string.h>#include<stdio.h>void main(){int pos=0;char c;FILE *fp;--------------- Missing Line-------------if (fp==NULL) {printf("Unable to open\n");return ; }while((c=fgetc(fp))!= EOF) {printf("%c",c); }fclose(fp);}Select one:fp = fopen("selfcode.c");*fp = fopen("selfcode.c","w");None of thesefp = fopen("selfcode.c","r");*fp = fopen("selfcode.c","r");
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.