0% found this document useful (0 votes)
32 views

File Processing

Notes for ANSI C File processing

Uploaded by

Abdul Moiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

File Processing

Notes for ANSI C File processing

Uploaded by

Abdul Moiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

12 FILE MANAGEMENT IN C

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.

12.2 DEFINING AND OPENING A FILE


396 Programming in ANSI C

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

otherwise an error occurs.

FILE *p1, *p2;


p1 = fopen(“data”, “r”);
p2 = fopen(“results”, “w”);
data is opened for reading and results is opened for writing. In case, the results
data
will occur.

r+
w+ Same as w
a+ Same as a

use.

12.3 CLOSING A FILE

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);
.....

12.4 INPUT/OUTPUT OPERATIONS ON FILES

are listed in Table 12.1.

The getc and putc


getc and putc. These are analogous to getchar and putchar
w
fp1. Then, the statement
putc(c, fp1);
writes the character contained in the character variable c FILE pointer fp1.
Similarly, getc
the statement
c = getc(fp2);

getc or putc. The getc will

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”);

/* Get a character from keyboard */


while((c=getchar()) != EOF)

/* Write a character to INPUT */


putc(c,f1);
/* Close the file INPUT */
fclose(f1);
printf(“\nData Output\n\n”);
/* Reopen the file INPUT */
f1 = fopen(“INPUT”,”r”);

/* Read a character from INPUT*/


while((c=getc(f1)) != EOF)

/* Display a character on screen */


printf(“%c”,c);

/* Close the file INPUT */


fclose(f1);
}

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

character, and displays it on the screen. Reading is terminated when getc


400 Programming in ANSI C

The getw and putw


The getw and putw getc and putc functions and
are used to read and write integer values. These functions would be useful when we deal with only
integer data. The general forms of getw and putw

putw(integer, fp);
getw( fp);
Program 12.2 illustrates the use of putw and getw functions.

DATA contains a series of integer numbers. Code a program


Program 12.2
ODD EVEN.

f1, f2 and f3.


containing integer values is created. The integer values are read from the terminal
DATA with the help of the statement
putw(number, f1);

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;

printf(“Contents of DATA file\n\n”);


f1 = fopen(“DATA”, “w”); /* Create DATA file */
for(i = 1; i <= 30; i++)
{
File Management in C 401

scanf(“%d”, &number);
if(number == -1) break;
putw(number,f1);
}
fclose(f1);

f1 = fopen(“DATA”, “r”);
f2 = fopen(“ODD”, “w”);
f3 = fopen(“EVEN”, “w”);

/* Read from DATA file */


while((number = getw(f1)) != EOF)
{
if(number %2 == 0)
putw(number, f3); /* Write to EVEN file */
else
putw(number, f2); /* Write to ODD file */
}
fclose(f1);
fclose(f2);
fclose(f3);

f2 = fopen(“ODD”,”r”);
f3 = fopen(“EVEN”, “r”);

printf(“\n\nContents of ODD file\n\n”);


while((number = getw(f2)) != EOF)
printf(“%4d”, number);

printf(“\n\nContents of EVEN file\n\n”);


while((number = getw(f3)) != EOF)
printf(“%4d”, number);

fclose(f2);
fclose(f3);

}
402 Programming in ANSI C

Output

Contents of DATA file


111 222 333 444 555 666 777 888 999 000 121 232 343 454 565 –1

Contents of ODD file


111 333 555 777 999 121 343 565

Contents of EVEN file


222 444 666 888 0 232 454

Fig. 12.2

The fprintf and fscanf

support two other functions, namely fprintf and fscanf


simultaneously.
The functions fprintf and fscanf perform I/O operations that are identical to the familar printf and
scanf
fprintf is
fprintf(fp, “control string”, list);
where fp
may include variables, constants and

fprintf(f1, “%s %d %f”, name, age, 7.5);


name is an array variable of type char and age is an int variable.
The general format of fscanf is
fprintf(fp, “control string”, list);

fscanf(f2, “%s %d”, item, &quantity);


scanf, fscanf
is reached, it returns the value EOF.

Program 12.3

Item name Number Price Quantity


File Management in C 403

the inventory table with the value of each item.

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];

printf(“Input file name\n”);


scanf(“%s”, filename);
fp = fopen(filename, “w”);
printf(“Input inventory data\n\n”);
printf(“Item name Number Price Quantity\n”);
for(i = 1; i <= 3; i++)
{
fscanf(stdin, “%s %d %f %d”,
item, &number, &price, &quantity);
fprintf(fp, “%s %d %.2f %d”,
item, number, price, quantity);
}
fclose(fp);
fprintf(stdout, “\n\n”);

fp = fopen(filename, “r”);

printf(“Item name Number Price Quantity Value\n”);


for(i = 1; i <= 3; i++)
{
404 Programming in ANSI C

fscanf(fp, “%s %d %f d”,item,&number,&price,&quantity);


value = price * quantity;
fprintf(stdout, “%-8s %7d %8.2f %8d %11.2f\n”,
item, number, price, quantity, value);
}
fclose(fp);
}

Output

Input file name


INVENTORY
Input inventory data

Item name Number Price Quantity


AAA-1 111 17.50 115
BBB-2 125 36.00 75
C-3 247 31.75 104

Item name Number Price Quantity Value


AAA-1 111 17.50 115 2012.50
BBB-2 125 36.00 75 2700.00
C-3 247 31.75 104 3302.00

Fig. 12.3

12.5 ERROR HANDLING DURING I/O OPERATIONS

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

The FILE pointer as its only

returns zero otherwise. If fp


if(feof(fp))
printf(“End of data.\n”);

The FILE pointer as its argument


and returns a nonzero integer if an error has been detected up to that point, during processing. It returns
zero otherwise. The statement
if(ferror(fp) != 0)
printf(“An error has occurred.\n”);
would print the error message, if the reading is not successful.

if(fp == NULL)
printf(“File could not be opened.\n”);

Program 12.4

NULL pointer test and function. When we

fopen(“TETS”, “r”);
returns a NULL

Similarly, the call

Program
#include <stdio.h>

main()
{
char *filename;
FILE *fp1, *fp2;
int i, number;

fp1 = fopen(“TEST”, “w”);


for(i = 10; i <= 100; i += 10)
putw(i, fp1);

fclose(fp1);
406 Programming in ANSI C

printf(“\nInput filename\n”);

open_file:
scanf(“%s”, filename);

if((fp2 = fopen(filename,”r”)) == NULL)


{
printf(“Cannot open the file.\n”);
printf(“Type filename again.\n\n”);
goto open_file;
}
else

for(i = 1; i <= 20; i++)


{ number = getw(fp2);
if(feof(fp2))
{
printf(“\nRan out of data.\n”);
break;
}
else
printf(“%d\n”, number);
}

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

Ran out of data.

Fig. 12.4

12.6 RANDOM ACCESS TO FILES

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,

reading or writing, a rewind is done implicitly.


fseek

fseek(file_ptr, offset, position);


is a number or variable of type long, and is
an integer number. The
The

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

When the operation is successful, fseek


fseek returns –1 (minus one). It is good practice to check
whether an error has occurred or not, before proceeding further.

Program 12.5 Write a program that uses the functions ftell and fseek.

A program employing ftell and fseek RANDOM

Character
stored – – – –> A B C ... Z

the end and printing the same on the screen.


n of
fseek(fp,n,0)

fseek(fp,–1L,2);

by the function
fseek(fp, –2L, 1);

or not. The loop is terminated as soon as it crosses it.


File Management in C 409

Program
#include <stdio.h>
main()
{
FILE *fp;
long n;
char c;
fp = fopen(“RANDOM”, “w”);
while((c = getchar()) != EOF)
putc(c,fp);

printf(“No. of characters entered = %ld\n”, ftell(fp));


fclose(fp);
fp = fopen(“RANDOM”,”r”);
n = 0L;

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’);

fseek(fp,–1L,2); /* Position to the last character */


do
{
putchar(getc(fp));
}
while(!fseek(fp,–2L,1));
fclose(fp);
}
Output

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

Fig. 12.5 fseek and ftell

Program 12.6

append()

are done under the control of a while n and is

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);

n = ftell(fp); /* Position of last character */


fclose(fp);

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>

void main(int argc, char *argv[ ])


{
FILE *fs;
Char str[100];
int i,n,j;

if(argc!=3)/*Checking the number of arguments given at command line*/


{
File Management in C 413

puts(“Improper number of arguments.”);


exit(0);
}

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);

fs=fopen(argv[1],”w”);/*Opening the file in write mode*/


if(n<0||n>strlen(str))
{
printf(“Incorrect value of n. Program will terminate...\n\n”);
getch();
exit(1);
}

j=strlen(str);
for (i=1;i<=n;i++)
{
fputc(str[j],fs);
j–;
}
fclose(fs);

printf(“\n%d characters of the file successfully printed in reverse order”,n);


getch();
}
414 Programming in ANSI C

Output
D:\TC\BIN\program source.txt 5
5 characters of the file successfully printed in reverse order

Fig. 12.7

12.7 COMMAND LINE ARGUMENTS


What is a command line argument? It is a parameter supplied to a program when the program is

X_FILE
we may use a command line like

where PROGRAM

parameters get into the program?


We know that every C program should have one main

main can take two arguments called argc and argv


main
the system.
argc
The argv
argc
argc is three and argv
argv[0] –> PROGRAM

main(int arge, char *argv[])


{
.....
.....
}
argv[0] always
represents the program name.

Program 12.8

main
arguments is 9.
File Management in C 415

The argument vector argv[1]


fp = fopen(argv[1], “w”);

Program
#include <stdio.h>

main(int arge, char *argv[])


{
FILE *fp;
int i;
char word[15];

fp = fopen(argv[1], “w”); /* open file with name argv[1] */


printf(“\nNo. of arguments in Command line = %d\n\n”,argc);
for(i = 2; i < argc; i++)
fprintf(fp,”%s “, argv[i]); /* write to file argv[1] */
fclose(fp);

/* Writing content of the file to screen */

printf(“Contents of %s file\n\n”, argv[1]);


fp = fopen(argv[1], “r”);
for(i = 2; i < argc; i++)
{
fscanf(fp,”%s”, word);
printf(“%s “, word);
}

fclose(fp);
printf(“\n\n”);

/* Writing the arguments from memory */

for(i = 0; i < argc; i++)


printf(“%*s \n”, i*5,argv[i]);
}

Output

C>F12_7 TEXT AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGG


416 Programming in ANSI C

No. of arguments in Command line = 9

Contents of TEXT file

AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG

C:\C\F12_7.EXE
TEXT
AAAAAA
BBBBBB
CCCCCC
DDDDDD
EEEEEE
FFFFFF
GGGGGG

Fig. 12.8

Just Remember









12.1 State whether the following statements are or .

(c) Files are always referred to by name in C programs.


(d) Using fseek
(e) Function fseek
12.2 Fill in the blanks in the following statements.
File Management in C 417

12.3 Describe the use and limitations of the functions getc and putc.

(a) getc and getchar


(b) printf and fprintf
(c) feof and ferror

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);

While ( (m = getw(fl) ) != EOF)


printf(“%5d”, m);

. . . .
for (i = 1; i <= 5; i++ )
{
fscanf(stdin, “%s”, name);
fprintf(fp, “%s”, name);
}
. . . .

(a) feof ()
(b) ferror ( )
and in a program.

12.19 When do we use the following functions?


(a) free ( )
(b) rewind ( )
418 Programming in ANSI C

integers.

on the screen.
If the offset value is a positive integer, then printing skips that many lines. If it is a negative

printed, if anything goes wrong.

include product code, cost and number of items available and are provided through keyboard.

You might also like