File Handling in Advance C
File Handling in Advance C
Aim
To study and perform program based on file handling and implement sequential access method.
Theory
A file represents a sequence of bytes on the disk where a group of related data is stored. File is
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function description
fopen() create a new file or open a existing file
General Syntax :
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened (or created)
file.
mode description
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.
In the above table we have discussed about various file I/O functions to perform reading and
writing on file. getc() and putc() are simplest functions used to read and write individual
characters to a file.
#include<stdio.h>
#include<conio.h>
main()
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
putc(ch,fp);
fclose(fp);
fp = fopen("one.txt", "r");
printf("%c",ch);
fclose(fp);
Output
#include<stdio.h>
#include<conio.h>
struct emp
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
fclose(p);
do
while( !feof(q) );
getch();
Output
In this program, we have create two FILE pointers and both are refering to the same file but in
different modes. fprintf() function directly writes into the file, while fscanf() reads from the file,
Conclusion
In this way we had studied and perform program based on sequential access method.