Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
122 views

C File Processing

This document discusses file processing in C language. It defines files as a collection of information stored outside of primary memory for permanent storage of data. There are two main types of files in C - sequential and random access files. The document also describes the data hierarchy from bits to bytes to fields to records to files. It explains how to define, open, read from and write to files in C using functions like fopen(), fclose(), fread(), fwrite() etc. and discusses sequential access files as an example.

Uploaded by

badshahsaad
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views

C File Processing

This document discusses file processing in C language. It defines files as a collection of information stored outside of primary memory for permanent storage of data. There are two main types of files in C - sequential and random access files. The document also describes the data hierarchy from bits to bytes to fields to records to files. It explains how to define, open, read from and write to files in C using functions like fopen(), fclose(), fread(), fwrite() etc. and discusses sequential access files as an example.

Uploaded by

badshahsaad
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

C FILE PROCESSING

INTRODUCTION:
Storage of data in variables and arrays is temporary; all such data is
lost when a program terminates. Files are used for permanent retention of
large amount of data. Computer store files on secondary storage devices,
especially disk storage device.
A file is a collection of information stored some where other than the
primary memory. Files are usually kept on disks. They are permanently
stored on external storage devices. Basically there are two types of files
used in the C language: sequential and random access file.
DATAHIERARCHY:
Data items processed by computers form a data hierarchy in which
data item become larger and more complex in structure as we progress from
bits, to characters(bytes), to files, and so on.
-BIT- smallest data item
Value of 0 or 1
-BYTE- 8 bits
Used to store a character.
-FIELD- group of characters conveying meaning
Example. Names
-RECORD- Group of related fields
.Representing by a struct or a class
Example In a payroll system, a record for a particular employee
that contained his/her identification number, name , and address. Hourly
salary rate, Number of exemptions claimed. Year-to-data earnings. Amount
of Federal taxes whitheld.
-Database- group of related files.

1
SALLY BLACK

FILE
TOM BLUE

JUDY GREEN

IRIS ORANGE

JUDY GREEN RECORDD

JUDY Field
01001000 Byte
1 Bit

DATA FILES:
Record key
identify a record to facilities the retrieval of specific records from a
file
Sequential file
Records typically sorted by key

FILES AND STREAMS


C views each file simply as a sequential stream of bytes. Each file ends
either with an end-of-file marker or at a specific byte number recorded in a
system maintained, administrative data structure. When a file is opened,
stream is associated with the file. Three files and their associated streams
are automatically opened when program execution begins-the standard input,
the standard output and the standard error. Streams provided
communication channels between file and program. For example, the
standard input stream enables a program to read data from the keyboard,
and the standard output stream enables a program to print data on the
screen. Opening a file returns a pointer to a FILE structure(defined in
<stdio.h>) that contains information used to process the file. This structure
includes a file descriptor i.e.. and index into an operating system array called
the open file table. Each array element contains a file control block(FCB)

2
that the operating system uses to administer a particular file. The standard
input, standard output and standard error are manipulated using file pointers
stdin,stdout and stderr.
0 1 2 3 4 5………………………………………………………………………………………..
End-of-file

The standard library provides many functions for reading data from
files and for writing data to files. Functions fgetc, like getchar, reads one
character from a fie. Function fgetc receives as an argument a FILE pointer
for the file from which a character will be read. The call fgetc(stdin) reads
one character form stdin- the standard input. This call is equivalent to the
call getchar(). Fuction fputc, like putchar , writes the character to stdout –
the standard output.
Several other functions used to read data from standard input and
write data to standard output have similarly named file-processing functions.
The fgets and fputs functions, for example, can be used to read a line from
a file and write a line to a file, respectively. Their counter parts, for reading
from standard input and writing to standard output, gets and puts. Some
more file processing functions are fscanf,fprintf and fread and fwrite.

DEFINING AND OPENING A FILE:


If we want to store data in a file in the secondary memory, we must
specify certain things about the file, to the operating system. They include
1.filename
2. data structure
3. purpose
File name is a string of characters that make up a valid file name for
the operating system. It may contain two parts, a primary name and an
optional period with the extension.
Examples: abc.dat
Xyz.txt
Prog.c
Stu.cpp
Data structure of a file is defined as FILE in the library of standard
I/O function definitions. Therefore, all files should be declared as type
FILE before they are used. FILE is a defined data type.

3
When we open a file, we must specify what we want to do with the
file. For example we may write data to the file or read the already exixting
data.
Following is the general format for declaring and opening a file
FILE *fptr;
Fptr=fopen(“filename”,”mode”);
The first statement declares the variables fp as a “pointer to the
data type FILE”. The second statement opens the file named file name and
assigns an identifier to the FILE type pointer fptr. This pointer, which
contains all the information about the file, is subsequently used as a
communication link between the system and the program.
The second statement also specifies the purpose of opening this file.
The mode does this job. Mode can be one of the following.

“r” Searches the file. If the file exists, loads it into memory and sets
up a pointer which points to the first character in it. If file doesn’t
exists it returns NULL.
Operations possible – reading from the file.
“w” Searches the file. If the file exists, its contents are overwritten.
If the file does’t exist, a new file is created. Return NULL, if
unable to open file.
Operations possible – writing to the file.
“a” Searches the file. If the file exists, loads it into memory and sets
up a pointer which points to the first character in it. If the file
does’t exist, a new file is created. Returns NULL, if unable to open
file.
Operations possible – appending new contents at end of file.
“r+” Searches file. If it exists, loads it into memory and sets up a
pointer which points to the first character in it. If the file
does’nt exist, a new file is created. Returns NULL, if unable to
open file.
Operations possible – reading existing contents, writing new
contents, modifying existing contents of the file.
“w+” Searchs file. If the file exists, its contents are destroyed. If the
file does’nt exists a new file is created. Returns Null, if unable to
open file.
Operations possible – writing new contents, reading them back
and modifying existing contents of the file.

4
“a+” Searches file. If the file exists, loads it into memory and sets up
a pointer which points to the first character in it. If the file
doesn’t exist, a new file is created. Returns NULL, if unable to open
file.
Operations possible – reading existing contents, appending new
contents to end of file. Cannot modify existing contents.

Note that both the filename and mode are specified as strings. They
should be enclosed in double quotation marks. Consider the following
statements:

FILE *p1,*p2;;
P1=fopen(“data”,”r”);
P2=fopen(“result”,”w”);

CLOSING A FILE:
A file must be closed as soon as all operations on it have been
completed. This ensures that all outstanding information associated with the
file is flushed out from the buffers and all links to the file are broken. It
also prevents any accidental misuse of the file. In case, there is a limit to
the number of files that can be kept open simultaneously, closing of
unwanted files might help open the required files. Another instance where
we have to close a file is when we want to reopen the same file in a different
modd. The I/O library supports a function to do this for us . It takes the
following form
fclose(file_ptr);
This would close the file associated with the FILE pointer file-pointer.
Ex: fclose(ptr1);
As a matter of fact all file are closed automatically whenever a program
terminates. However, closing a file as soon as you are done with it is a good
programming habit.

CREATING A SEQUENTIAL-ACCESS FILE


C imposes no structure for a file. Thus, notions like a record of a file
do not exist as part of the C language. Therefore, the programmer must
provide any file structure to meet the requirement of each particular
application.

5
The following program creates a simple sequential –access file that
might be used in an accounts receivable system to help keep track of the
amounts owed by a company’s credit clients.

/*Program to create sequential access file */


#include<stdio.h>
#include<conio.h>
void main()
{
int account;
char name[30];
double balance;
FILE *cfptr;/* cfptr=clients.dat file pointer*/
if((cfptr=fopen("clients.dat","w"))==NULL)
printf("File could not be searche");
else
{
printf("Enter the account,name and balance((ctrl+z) to stop input)\n");
scanf("%d%s%lf",&account,name,&balance);
while(!feof(stdin))
{
fprintf(cfptr,"%d%s%.2f",account,name,balance);
scanf("%d%s%lf",&account,name,&balance);
}
fclose(cfptr);
}
}
OUTPUT: Enter the account, name and balance ( (ctrl+z) to stop input)
100 Jones 24.98
200 Doe 345.67
300 White 0.00
400 Stone -42.16
500 Rich 224.62
The statement
FILE *cfptr;
States that cfptr is a pointer to a FILE structure. The C program
administers each file with a separate FILE structure. The programmer need

6
not know the specifics of a FILE structure to use files. The FILE structure
leads indirectly to the operating system’s file control block(FCB) for a file.
Each open file must have a separately declared pointer of type FILE that is
used to refer to the file. The line
if(cfptr=fopen(“clients.dat”,”w”))==NULL)
Names the clients.dat to be used by the program and establishes a “line of
communication
“ with the file. The file pointer cfptr is assigned a pointer to the FILE
structures for the file opened with fopen. Function fopen takes two
arguments : a file name and a file open mode. The file open mode “w”
indicated that the file is to be opened for writing. If a file does not exist
and it is opened for writing. , fopen creates the file. If an existing file is
opened for writing, the contents of the file are discarded without warning.
IN the program, the if structure is used to determine whether the file
pointer cfptr is NULL(i.e. the file is not opened). If it is NULL, an error
message is printed and the program ends. Otherwise, the input processed
and written to the file.
The line
while(!feof(stdin))
Used function feof to determine whether the end-of-file indicator is set for
the file to which stdin refers. The end-of-file indicator informs the program
that there is no more data to be processed. The argument to function feof
is a pointer to the file being tested fot the end-of-file indicator has been
set: otherwise, zero is returned. The while structure that includes the feof
call in this program continues executing while the end-of-file indicator is not
set.
The statement
fprintf(cfptr,”%d %s %.2f”,account,name,balance);
Writes data to the file clients.dat the data may be retrieved later by a
program designed to read the file. Function fprintf is equivalent to printf
except that fprintf also receives as an argument a file pointer for the file
to which the data will be written.
After the user enters end-of-file, the program closes the clients.dat
file with fclose and terminates. Function fclose also receives the file
pointer(rather than the file name) as an argument. If function fclose is not
called explicitly, the operating system normally will close the file when
program execution terminates.

7
READING DATA FROM A SEQUENTIAL –ACCESSFILE
/*Prgram to read data from a sequential file*/
#include<stdio.h>
#include<conio.h>
void main()
{
int account;
char name[30];
double balance;
FILE *cfptr;/*cfptr=clients.dat fil pointer*/
if((cfptr=fopen("clients.dat","r"))==NULL)
printf("File could not be opened\n");
else
{
printf("%s\t%s\t%s\n","Account","Name","Balnce");
fscanf(cfptr,"%d%s%lf",&account,name,&balance);
while(!feof(cfptr))
{
printf("%d\t%s\t%f\n",account,name,balance);
fscanf(cfptr,"%d%s%lf",&account,name,&balance);
}
fclose(cfptr);
}
}
OUTPUT:
Account Name Balance
100 Jones 24.98
200 Doe 345.67
300 White 0.00
400 Stone -42.16
500 Rich 224.62

The statement
FILE *cfptr;
Indicates cfptr is a pointer to a FILE.
The line
If(cfptr=fopen(“clients.dat”,”r”))==NULL)

8
Attempts to open the file “clients.dat” for reading (“r”) and determines
whether the file is opened successfully (i.e fopen does not return NULL).

The statement
fscanf(cfptr,”%d%s%f”,&account,name,&balance);
Reads a “record” from the file.. Function fscanf is equivalent to function
scanf except fscanf receives as an argument a file pointer for the file from
which the data is read. After the preceding statement is executed the first
time, accont will have the value 100, name will have the “jones” and balance
will have the value 24.98. Each time the second fscanf statement is
executed, another record is read from the file an account, name and balance
take on new values. When the end of the file is reached, the files closed and
the program terminates.

RANDOM-ACCESS FILES
Individual records of a randomly accessed file are accessed directly
(and thus quickly).with out searching through other records. This make
randomly accessed files appropriate for airline reservation systems, banking
systems, point-of-sale systems, and other kinds of transaction processing
systems that require rapid access to specific data.
Data can be inserted in a randomly accessed file with out destroying
other data in the file. Data stored previously can also be updated or deleted
without rewriting the entire file.
CREATING A RANDOMLY ACCESSING FILE
Function fwrite transfers a specified number a bytes beginning at a
specified location in memory to a file. The data is written beginning at the
location in the file indicated by the file position pointer. Function fread
transfers a specified number of bytes from the location in the file specified
by the file position pointer to an area in memory beginning with a specified
address. Now, when writing an integer, instead of using

fprintf(fptr,”%d”,number);
Which could print as few as 1 digits or as many as 11 digits( 10 digits plus a
sign, each of which requires 1 byte of storage) for a 4-byte integer, we can
use

fwrite(&number,sizeof(int),1,ptr);
&number –location to transfer bytes from

9
sizeof(int) —Number of bytes to transfer
1- For arrays, number of elements to transfer
-In this case, “one element” of an array is being transferred
myPtr – File to transfer to or form

Function fwrite and fread are capable of reading and writing array of
data to and from disk. The third argument of both fread and fwrite is the
number of elements in the array that should be read from disk or written to
disk. The preceding fwrite function call writes a single integer to disk So the
third argument is 1(as if one element of an array is begin written).
Writing structs
fwrite(&myobject,sizeof(struct mystruct),1,myptr);
sizeof – returns size in bytes of object in paranthesis

/*creating a randomly accessed file sequentially*/


#include<stdio.h>
#include<conio.h>
struct clientData
{
int acctNum;
char lastName[15];
char firstName[10];
double balance;
};
void main()
{
int i;
struct clientData blankclient ={0,"","",0.0};
FILE *cfptr;
if((cfptr=fopen("credit.dat","w"))==NULL)
printf("File could not be opened\n");
else
{
for(i=1;i<=100;i++)
fwrite(&blankclient,sizeof(struct clientData),1,cfptr);
fclose(cfptr);
}
}

10
WRITIN DATA RANDOMLY TO A RANDOMLEY ACCESSED FILE
The following program writes data to the file “credit.dat”. It uses the
combination of fseek and fwrite to strore data at specific locations in the
file. Funcion fseek sets the file position pointer to a specific position in the
file, then fwrite writes the data.

The ANSI standard shows the function prototypes for fseek as


fseek(pointer,offset,symbolic_constants);
pointer-pointer to file
offset- file position pointer(0 is first location)
symbolic constant_specific where in file we are reading from
SEEK_SET – seek starts at beginning of file
SEEK_CUR – seek starts at current location in file
SEEK_END – seek starts at end of file

Example:
/*Writing to a random access file*/
#include<stdio.h>
#include<conio.h>
struct clientData
{
int acctNum;
char lastName[15];
char firstName[10];
double balance;
};
void main()
{
FILE *cfptr;
struct clientData client={0,"","",0.0};
if((cfptr=fopen("credit.dat","r+"))==NULL)
printf("File could not be opened\n");
else
{
printf("Enter account number (1 to 100, 0 to end input\n");
scanf("%d",&client.acctNum);
while(client.acctNum!=0)

11
{
printf("Enter lastname,firstname,balance\n");
fscanf(stdin,"%s%s%lf",client.lastName,client.firstName,&client.balance);
fseek(cfptr,(client.acctNum-1)*sizeof(struct clientData),SEEK_SET);
fwrite(&client,sizeof(struct clientData),1,cfptr);
printf("Enter account number\n");
scanf("%d",&client.acctNum);
}
fclose(cfptr);
}
}
OUTPUT:
Enter account number(1 to 100, 0 to end input)
37
Enter lastname, firstname, balance
Barker Doug 0.00
Enter account number(1 to 100, 0 to end input)
29
Enter lastname, firstname, balance
Brown Nancy -24.54
Enter account number(1 to 100, 0 to end input)
33
Enter lastname, firstname, balance
Dunn Stacey 314.33
Enter account number(1 to 100, 0 to end input)
0
READING DATA RANDOMLY FROM A RANDOMLY ACCESSED FILE:
Function fread reads a specified number of bytes from a file into
memory. For example, the statement
fread(&client,sizeof(struct clientData),1,cfptr);
reads the number of bytes determined by sizeof(struct clientData) from
the file referenced by cfptr and stores the data in the structure client.
The bytes are read from the location in the file specified by the file
position pointer. Function fread can be used to read several fixed-size array
elements by providing a pointer to the array in which the elements will be
stored, and by indicating the number of elements to be read. The preceding
statement specifies that one element should be read. To read more than one

12
element, specify the number of elements in the third argument of the fread
statement.

/* Reading a random access file sequentially*/


#include<stdio.h>
#include<conio.h>
struct clientData
{
int acctNum;
char lastName[15];
char firstName[10];
double balance;
};
void main()
{
FILE *cfptr;
struct clientData client ={0,"","",0.0};
clrscr();
if((cfptr=fopen("credit.dat","r"))==NULL)
printf("File could not be opened\n");
else
{
printf("%s\t%s\t%s\t%sn","Acct","Last Name","First Name","Balance");
while(!feof(cfptr))
{
fread(&client,sizeof(struct clientData),1,cfptr);
if(client.acctNum!=0)
printf("\n%d\t%s\t%s\t
%f\n",client.acctNum,client.lastName,client.firstName,client.balance);
}
fclose(cfptr);
}
}

OUTPUT:
Acct LastName FirstName Balance
29 Brown Nancy -24.54
33 Dunn Stacey 314.33

13
37 Barker Doug 0.0
88 smith Dave 258.34

getc() and putc() functions


The simplest file I/O functions are getc( ) and putc( ). These are
analogous to getchar( ) and putchar( ). Assume that a file is opened with
mode w and file pointer fp1. Then, the statement
putc(c,fp1);
Writes the character contained in the character variable ‘c’ to the file
associated with FILE pointer fp1. Similarly getc() is used to read a
character from a file that has been opened in read mode. For example, the
statement
C=getc(fp1);
Would read a character from the file whose file pointer if fp1.
Example:
/*Character oriented read/write operations on a file*/
/*Using getc( ) and put( ) */
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1;
char c;
clrscr();
printf("Enter data for the file\n");
f1=fopen("student","w");
while((c=getchar())!=EOF)
{
putc(c,f1);
}
fclose(f1);
printf("\The data in the file is\n\n");
f1=fopen("student","r");
while((c=getc(f1))!=EOF)
putchar(c);
fclose(f1);
getch();
}

14
OUTPUT:
Enter the data to the file
Twinkle Twinkle Little star
Data in the file is
Twinkle Twinkle Little star

getw() and putw() functions


The getw and putw are interger-oriented functions. They are similar
to the 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 are
putw(integer,fp);
getw(fp);
Example:

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1,*f2,*f3;
int number,i;
clrscr();
printf("Enter contents of data files\n");
f1=fopen("data","w");
for(i=1;i<30;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");
while((number=getw(f1))!=EOF)
{
if(number%2==0)

15
putw(number,f3);
else
putw(number,f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("odd","r");
f3=fopen("even","r");
printf("\n Contets of odd file\n");
while((number=getw(f2))!=EOF)
printf("%d\t",number);
printf("\nContets of even file\n");
while((number=getw(f3))!=EOF)
printf("%d\t",number);
fclose(f2);
fclose(f3);
getch();
}
OUTPUT:
Enter contents of data file
1 2 3 4 5 6 7 8 9 10 -1
Contents of odd file
13579
Contets of even file
2 4 6 8 10
fprintf() and fscanf() functions
The fprintf and fscanf functions can handle a group of mixed
data simultaneously
fprintf(fp,”controlstring”,list);
Example: fprintf(fp,”%s %d %f”,name,age,sal);

The general format of fscanf is


fscanf(fp,”control string”,list);

Example:

16
/* Program to read student information from keyboard and write it on to
file and displaying details on the output device*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int no;
char name[30];
int m1,m2,m3;
char ans='y';
FILE *fp;
clrscr();
fp=fopen("text.dat","w");
if(fp==NULL)
{
printf("The file cannot be opened");
exit(0);
}
while(ans!='n'&&ans!='N')
{
fflush(stdin);
printf("Enter the details of a student\n");
printf("STUDENT NAME :");
scanf("%s",name);
printf("STUDENT ROLL NO :");
scanf("%d",&no);
printf("MARKS IN THREE SUBJECTS\n");
printf("PHYSICS :");
scanf("%d",&m1);
printf("CHEMISTRY :");
scanf("%d",&m2);
printf("MATHEMATICS :");
scanf("%d",&m3);
fprintf(fp,"%s\t\t%d\t\t%d %d %d\n",name,no,m1,m2,m3);
printf("Do u want to enter another student details\n");
fflush(stdin);
scanf("%c",&ans);

17
}
fclose(fp);
fp=fopen("text.dat","r");
while(!feof(fp))
{
fscanf(fp,"%s%d%d%d%d",name,&no,&m1,&m2,&m3);
fprintf(stdout,"%s\t%d\t%d\t%d\t%d\n",name,no,m1,m2,m3);

}
fclose(fp);
getch();
}
OUTPUT:
Enter the details of student
STUDENT NAME : xyz
STUDENT ROLL NUMBER: 810
MARKS IN THREE SUBJECTS:
PHYSCIS : 98
CHEMISTRY : 88
MATHEMATICS: 99
Do u want to enter another student details
Y
STUDENT NAME : pqr
STUDENT ROLL NUMBER: 811
MARKS IN THREE SUBJECTS:
PHYSCIS : 94
CHEMISTRY : 85
MATHEMATICS: 69
Do u want to enter another student details
n

xyz 810 98 88 99
pqr 811 94 85 69

ftell( ) and fseek( )


fseek( ) provides random access to the file i.e it enables file pointer
be positioned at any part of the file.

18
The general format is
fseek(fp,nL,mode);
fp – file pointer
nL – No of bytes
mode:
0 - move the file pointer always from the beginning of the file
1 - move the file pointer always from the current position of the file
2 - move the file pointer from the end of the file.

ftell() returns the no of bytes from the beginning of file upto the
current position of the pointer.
long r;
r=ftell(fp);

Example:
/*Demonstrating ftell( ) and fseek() functions */

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1;
long n,curpos;
char c;
clrscr();
f1=fopen("info","w+");
while((c=getchar())!=EOF)
{
putc(c,f1);
}
curpos=ftell(f1);
printf("The position of file pointer is %ld\n",curpos);
n=0;
fseek(f1,n,0);
curpos=ftell(f1);
while((c=getc(f1))!=EOF)
{
printf("Position of %c is %ld\n",c,curpos);

19
n=n+5;
fseek(f1,n,0);
curpos=ftell(f1);
}
fclose(f1);
getch();
}
OUTPUT:
abcdefghijklmnopqrstuvwxyz ^z
The position of file pointer is 26
Position of a is 0
Position of f is 5
Position of k is 10
Position of p is 15
Position of u is 20
Position of z is 25

K RAVI KUMAR
Asst. Prof
CSED

20

You might also like