Files
Files
Files
The entire data is lost when either the program is terminated or computer is turned off
therefore it is necessary to have more flexible approach where data can be stored on the
disks and read whenever necessary, without destroying the data. This method employs the
concept of files to store data. Thus, files allow us to store information permanently on the
disk; it can be accessed and can further be altered depending upon the needs. This process
leads to the concept of data files.
Definition:
File is a set of records that can be accessed through a set of library functions.
File Types:
Sequential file:
In this type data are kept sequentially.
If we want to read last record of the file we need to read all the records before
reading that record.
It takes more time.
Random access file:
In this type data can be read and modified randomly.
If we want to read last record of the file, we can read it directly.
It takes less time.
File Functions:
fopen() - Creates and Open a new file and returns a pointer to the file.
Mode: a (append)
When a file is opened for appending, it will be created if it does not already exist
and it will be initially empty.
If it does exist, the data input point will be positioned at the end of the present
data so that any new data will be added to any data that already exists in the file.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fp;
char c;
clrscr();
printf("Contents of file before appending:\n");
fp=fopen("data.txt","r");
while(!feof(fp))
{
c=getc(fp);
printf("%c",c);
}
fp=fopen("data.txt","a");
getch();
}
Sample Input and Output:
Contents of file before appending:
I am studying in RGCET.
Write data to append and to - stop press '.'
This is file concept example.
Contents of file after appending:
I am studying in RGCET.This is file concept example.
fgetc():
This function is similar to getc() function. It also reads a character and increases the file
pointer position. If any error or end of file is reached it returns EOF.
#include <stdio.h>
sam.txt (file)
I am
Working in File concept.
Sample Output:
I am
Working in File concept.
Note:
The getc and putc functions are analogous to getchar and putchar functions and handle
one character at a time. The putc function writes the character contained in character
variable c to the file associated with the pointer fp1.
Example putc(c,fp1);
similarly getc function is used to read a character from a file that has been open in read
mode. c=getc(fp2).
fputc():
void main() {
FILE *fp1, *fp2;
char ch;
clrscr();
while (1) {
ch = fgetc(fp1);
if (ch == EOF)
break;
else
putc(ch, fp2);
}