C File
C File
Background:
Data files
Many applications require that information be “written & read” from an auxiliary storage
device. This information is written in the form of Data Files. Data files allow us to store
information permanently and to access and alter that information whenever necessary.
Types of Data files
Standard data files. (Stream I/O)
System data files. (Low level I/O)
Standard I/O
Easy to work with, & have different ways to handle data.
Four ways of reading & writing data:
1. Character I/O.
2. String I/O.
3. Formatted I/O.
4. Record I/O.
File Protocol
1. fopen
2. fclose
fopen:-
Syntax:
It is used to open a file.
fopen (file name , access-mode ).
“r” open a file for reading only.
“w” open a file for writing.
“a” open a file for appending .
“r+” open an existing file for reading & writing.
“w+” open a new file for reading &writing.
“a+” open a file for reading & appending & create a new file if it does exist.
Example:-
#include <stdio.h>
main
{
FILE*fpt;
fpt = fopen (“first.txt”,”w”);
fclose(fpt);
}
Establish buffer area, where the information is temporarily stored before being transferred b/w
the computer memory & the data file.
file is a special structure type that establishes the buffer area.
fpt is a pointer variable that indicates the beginning of buffer area.
fpt is called stream pointer.
fopen stands for File Open.
A data file must be opened before it can be created or processed.
Standard I/O:
Four way s of reading and writing data:
Character I/O.
String I/O.
Formatted I/O.
Record I/O.
Character I/O:
In normal C program we used to use getch, getchar and getche etc.
In filling we use putc and getc.
putc( );
It is used to write each character to the data file.
Putc requires specification of the stream pointer *fpt as an argument.
Syntax:
putc(c, fp);
c = character to be written in the file .
fp = file pointer .
putch or putchar writes the I/P character to the consol while putc writes to the file.
Some example:
1. Write a program that read first n numbers in a file and display in another file
Program code:
#include<stdio.h>
int main()
{
int i, n, a[100];
FILE *fp, *fo;
fp = fopen("in.txt", "r");
fo = fopen("out.txt", "w");
printf("How many numbers: ");
scanf("%d", &n);
for(i=0; i<n; i++)
fscanf(fp, "%d", &a[i]);
for(i=0; i<n; i++)
fprintf(fo, " %d", a[i]);
return 0;
}
2. Write a program that read all numbers from a file Data.txt and display even
numbers in Even.txt, odd numbers in Odd.txt.
Program code:
#include<stdio.h>
int main()
{
int n;
FILE *fin, *fe, *fo;
fin = fopen("Data.txt", "r");
fe = fopen("Even.txt", "w");
fo = fopen("Odd.txt", "w");