fopen() is used to open and fclose() is used to close a file in C
#include <stdio.h> #include <stdlib.h> // For exit() int main() { FILE *fptr; char filename[100], c; printf("Enter the filename to open \n"); scanf("%s", filename); // Open file fptr = fopen(filename, "r"); if (fptr == NULL) { printf("Cannot open file \n"); exit(0); } // Read contents from file c = fgetc(fptr); while (c != EOF) { printf ("%c", c); c = fgetc(fptr); } fclose(fptr); return 0; } |
chevron_right
filter_none
Output:
Enter the filename to open a.txt /*Contents of a.txt*/
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- C program to copy contents of one file to another file
- C program to print odd line contents of a File followed by even line content
- Write a C program that displays contents of a given file like 'more' utility in Linux
- C Program to merge contents of two files into a third file
- Program to copy the contents of one array into another in the reverse order
- C++ program to print unique words in a file
- Print "Hello World" in C/C++ without using any header file
- C program to print a string without any quote (singe or double) in the program
- C Program to count number of lines in a file
- C program to delete a file
- C Program for Lower Case to Uppercase and vice-versa in a file
- C++ program to read file word by word
- C++ program to append content of one text file to another
- Program to delete a line given the line number from a file
- LEX program to add line numbers to a given file
- C Program to find size of a File
- Lex program to take input from file and remove multiple spaces, lines and tabs
- C++ program to create a file
- C Program to count the Number of Characters in a File
- Write a C program to print "Geeks for Geeks" without using a semicolon

