BY TEJAS
It's new to read the .txt file in C to many beginners and programmers. Most of them don't know "actually it is possible or not" to read the file in C. But it is possible. So, how we can do that program.
So let's take a turn to our program.
What is exactly a program do?
Let assume we want to see the content of the abc.txt file, so we write a program for that and in output that file's content we can see. It is a very simple program.
So that we use fopen function which is predefined in C. If the file is open correctly, then it returns the pointer to the file, and if it is not opened, then it returns NULL for that.
For opening the file, we need the .txt file and C program file in the same directory.
In below Image there is the Output of this Program
In this program, we use so many predefined functions like fopen
, fclose
, fgetc
, etc. We use 'if' statement for showing if the file is not opening then print the "error while opening the file."
We have opened just one file in this program, but you can open so many files in one program.
below here is a C code program and output of C program.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp;
printf("Enter name of a file you wish to see\n");
gets(file_name);
fp = fopen(file_name, "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:\n", file_name);
while((ch = fgetc(fp)) != EOF)
printf("%c", ch);
fclose(fp);
return 0;
}
Enter the name of file you wish to see
programtuts.txt
The contents of programtuts.txt file are :
Please Share ProgramTuts.com for best programming examples.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp;
printf("Enter name of a file you wish to see\n");
gets(file_name);
fp = fopen(file_name, "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:\n", file_name);
while((ch = fgetc(fp)) != EOF)
printf("%c", ch);
fclose(fp);
return 0;
}
Enter the name of file you wish to see
programtuts.txt
The contents of programtuts.txt file are :
Please Share ProgramTuts.com for best programming examples.