File Processing
File Processing
Key Terms
Filename I ftell I rewind I fseek I Command line argument
12.1 INTRODUCTION
Until now we have been using the functions such as scanf and printf to read and write data. These are
console oriented I/O functions, which always use the terminal (keyboard and screen) as the target place.
data and in such situations, the console oriented I/O operations pose two major problems.
1. It becomes cumbersome and time consuming to handle large volumes of data through terminals.
2. The entire data is lost when either the program is terminated or the computer is turned off.
read whenever necessary, without destroying the data. This method employs the concept of to store
∑
∑
∑
∑
∑
low-level I/O
and uses UNIX system calls. The second method is referred to as the high-level I/O operation and uses
that are available in the C library. They are listed in Table 12.1.
There are many other functions. Not all of them are supported by all compilers. You should check
your C library before using a particular I/O function.
Table 12.1
Operation
fopen()
fclose()
getc()
putc()
fprintf()
fscanf()
getw()
putw()
fseek()
ftell()
bytes from the start).
rewind()
1. Filename.
2. Data structure.
3. Purpose.
Filename
contain two parts, a primary name and an optional period
Input.data
store
PROG.C
Student.c
FILE
FILE
FILE *fp;
fp = fopen(“filename”, “mode”);
fp as a “pointer to the data type FILE”. As stated earlier,
FILE
FILE type pointer fp. This pointer, which contains all the information
File Management in C 397
r
w
a
r+
w+ Same as w
a+ Same as a
use.
fclose(file_pointer);
FILE pointer
of a program.
.....
.....
FILE *p1, *p2;
p1 = fopen(“INPUT”, “w”);
p2 = fopen(“OUTPUT”, “r”);
398 Programming in ANSI C
.....
.....
fclose(p1);
fclose(p2);
.....
INPUT,
Program 12.1 again read the same data from the INPUT
A program and the related input and output data are shown in Fig.12.1. We enter the input data via
INPUT. The end of the data
is indicated by entering an EOF character, which is in the reference system. (This may be
Program
#include <stdio.h>
main()
{
File Management in C 399
FILE *f1;
char c;
printf(“Data Input\n\n”);
/* Open the file INPUT */
f1 = fopen(“INPUT”, “w”);
Output
Data Input
This is a program to test the file handling
features on this system^Z
Data Output
This is a program to test the file handling
features on this system
Fig. 12.1
putw(integer, fp);
getw( fp);
Program 12.2 illustrates the use of putw and getw functions.
DATA for reading, ODD and EVEN for writing. The contents of DATA
integer by integer, by the function getw(f1) and written to ODD or EVEN
Note that the statement
(number = getw(f1)) != EOF
reads a value, assigns the same to number
ODD and EVEN opened for writing are closed before they are reopened for reading.
Program
#include <stdio.h>
main()
{
FILE *f1, *f2, *f3;
int number, i;
scanf(“%d”, &number);
if(number == -1) break;
putw(number,f1);
}
fclose(f1);
f1 = fopen(“DATA”, “r”);
f2 = fopen(“ODD”, “w”);
f3 = fopen(“EVEN”, “w”);
f2 = fopen(“ODD”,”r”);
f3 = fopen(“EVEN”, “r”);
fclose(f2);
fclose(f3);
}
402 Programming in ANSI C
Output
Fig. 12.2
Program 12.3
is read using the function fscanf stdin, which refers to the terminal and it is then written to
fp. fp
Program
#include <stdio.h>
main()
{
FILE *fp;
int number, quantity, i;
float price, value;
char item[10], filename[10];
fp = fopen(filename, “r”);
Output
Fig. 12.3
If we fail to check such read and write errors, a program may behave abnormally when an error
occurs. An unchecked error may result in a premature termination of the program or incorrect output.
and that can help us detect I/O
File Management in C 405
if(fp == NULL)
printf(“File could not be opened.\n”);
Program 12.4
fopen(“TETS”, “r”);
returns a NULL
Program
#include <stdio.h>
main()
{
char *filename;
FILE *fp1, *fp2;
int i, number;
fclose(fp1);
406 Programming in ANSI C
printf(“\nInput filename\n”);
open_file:
scanf(“%s”, filename);
fclose(fp2);
}
Output
Input filename
TETS
Cannot open the file.
Type filename again.
TEST
10
20
30
40
50
File Management in C 407
60
70
80
90
100
Fig. 12.4
reading the other parts. This can be achieved with the help of the functions fseek, ftell, and rewind
available in the I/O library.
ftell that corresponds to the current position.
n = ftell(fp);
n would give the relative offset (in bytes) of the current position. This means that n bytes have already
been read (or written).
rewind
rewind(fp);
n = ftell(fp);
would assign 0 to n rewind. Remember,
1 Current position
The offset may be positive, meaning move forwards, or negative, meaning move backwards.
fseek
408 Programming in ANSI C
Table 12.2
Statement Meaning
Go to the beginning.
(Similar to rewind)
Stay at the current position.
(Rarely used)
Go forward by m bytes.
Go backward by m bytes from the current position.
Go backward by m bytes from the end. (Positions
Program 12.5 Write a program that uses the functions ftell and fseek.
Character
stored – – – –> A B C ... Z
fseek(fp,–1L,2);
by the function
fseek(fp, –2L, 1);
Program
#include <stdio.h>
main()
{
FILE *fp;
long n;
char c;
fp = fopen(“RANDOM”, “w”);
while((c = getchar()) != EOF)
putc(c,fp);
while(feof(fp) == 0)
{
fseek(fp, n, 0); /* Position to (n+1)th character */
printf(“Position of %c is %ld\n”, getc(fp),ftell(fp));
n = n+5L;
}
putchar(‘\n’);
ABCDEFGHIJKLMNOPQRSTUVWXYZ^Z
No. of characters entered = 26
Position of A is 0
Position of F is 5
410 Programming in ANSI C
Position of K is 10
Position of P is 15
Position of U is 20
Position of Z is 25
Position of is 30
ZYXWVUTSRQPONMLKJIHGFEDCBA
Program 12.6
append()
Program
#include <stdio.h>
struct invent_record
{
char name[10];
int number;
float price;
int quantity;
};
main()
{
struct invent_record item;
char filename[10];
int response;
FILE *fp;
long n;
void append (struct invent_record *x, file *y);
printf(“Type filename:”);
scanf(“%s”, filename);
File Management in C 411
fp = fopen(filename, “a+”);
do
{
append(&item, fp);
printf(“\nItem %s appended.\n”,item.name);
printf(“\nDo you want to add another item\
(1 for YES /0 for NO)?”);
scanf(“%d”, &response);
} while (response == 1);
fp = fopen(filename, “r”);
while(ftell(fp) < n)
{
fscanf(fp,”%s %d %f %d”,
item.name, &item.number, &item.price, &item.quantity);
fprintf(stdout,”%-8s %7d %8.2f %8d\n”,
item.name, item.number, item.price, item.quantity);
}
fclose(fp);
}
void append(struct invent_record *product, File *ptr)
{
printf(“Item name:”);
scanf(“%s”, product–>name);
printf(“Item number:”);
scanf(“%d”, &product–>number);
printf(“Item price:”);
scanf(“%f”, &product–>price);
printf(“Quantity:”);
scanf(“%d”, &product–>quantity);
fprintf(ptr, “%s %d %.2f %d”,
product–>name,
product–>number,
product–>price,
product–>quantity);
}
412 Programming in ANSI C
Output
Type filename:INVENTORY
Item name:XXX
Item number:444
Item price:40.50
Quantity:34
Item XXX appended.
Do you want to add another item(1 for YES /0 for NO)?1
Item name:YYY
Item number:555
Item price:50.50
Quantity:45
Item YYY appended.
Do you want to add another item(1 for YES /0 for NO)?0
AAA-1 111 17.50 115
BBB-2 125 36.00 75
C-3 247 31.75 104
XXX 444 40.50 34
YYY 555 50.50 45
Fig. 12.6
Program 12.7
Program
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
n=atoi(argv[2]);
fs = fopen(argv[1], “r“);/*Opening the souce file in read mode*/
if(fs==NULL)
{
printf(“Source file cannot be opened.”);
exit(0);
}
i=0;
while(1)
{
if(str[i]=fgetc(fs)!=EOF)/*Reading contents of file character by character*/
j=i+1:
else
break;
}
fclose(fs);
j=strlen(str);
for (i=1;i<=n;i++)
{
fputc(str[j],fs);
j–;
}
fclose(fs);
Output
D:\TC\BIN\program source.txt 5
5 characters of the file successfully printed in reverse order
Fig. 12.7
X_FILE
we may use a command line like
where PROGRAM
Program 12.8
main
arguments is 9.
File Management in C 415
Program
#include <stdio.h>
fclose(fp);
printf(“\n\n”);
Output
C:\C\F12_7.EXE
TEXT
AAAAAA
BBBBBB
CCCCCC
DDDDDD
EEEEEE
FFFFFF
GGGGGG
Fig. 12.8
Just Remember
∑
∑
∑
∑
∑
∑
∑
∑
∑
∑
12.3 Describe the use and limitations of the functions getc and putc.
12.8 What are the common uses of rewind and ftell functions?
fseek function?
rewind(fp); and fseek(fp,0L,0);?
FILE fptr;
fptr = fopen (“data”, “a+”);
12.12 What does the following statement mean?
FILE(*p) (void)
12.13 What does the following statement do?
While ( (c = getchar( ) != EOF )
putc(c, fl);
. . . .
for (i = 1; i <= 5; i++ )
{
fscanf(stdin, “%s”, name);
fprintf(fp, “%s”, name);
}
. . . .
(a) feof ()
(b) ferror ( )
and in a program.
integers.
on the screen.
If the offset value is a positive integer, then printing skips that many lines. If it is a negative
include product code, cost and number of items available and are provided through keyboard.