Knowee
Questions
Features
Study Tools

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.

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. Include the necessary header files:
#include <stdio.h>
  1. Declare the main function:
int main() {
    // Code goes here
    return 0;
}
  1. Declare a file pointer variable to hold the reference to the file:
FILE *file;
  1. 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.

  1. Check if the file was opened successfully:
if (file == NULL) {
    printf("Failed to open the file.\n");
    return 1;
}
  1. Read the content of the file using a loop:
char ch;
while ((ch = fgetc(file)) != EOF) {
    printf("%c", ch);
}
  1. Close the file using the fclose function:
fclose(file);
  1. 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.

This problem has been solved

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)

1/1

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.