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

Chapter 12 Files Management in C

Uploaded by

MD Saidur Rahman
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Chapter 12 Files Management in C

Uploaded by

MD Saidur Rahman
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 48

Chapter 12 Files Management In C

1
12.1 Introduction
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.
To employ the concept of file to store data
A file is a place on the disk where a group
of related data is stored.
Functions to Perform Basic File
Operation
naming a file
opening a file
reading data from a file
writing data to a file
closing a file
High Level I/O Functions
Function Operation
fopen() *Create a new file for use
*Opens an existing file for use
fclose() *Closes a file which has been opened for use
getc() *Reads a character from a file
puts() *Writes a character to a file
fprintf() *Writes a set of data values to a file
fscanf () *Reads a set of data values from a file
getw() *Reads an integer form a file
putw() *Writes an integer to a file
fseek() *Sets the position to a desired point in the file
ftell() *Gives the current position in the file
rewind() *Sets the position to the beginning of the file
12.2 Defining and Opening a
File
The certain things about the file to the
operation system include:
– 1. Filename
– 2. Data structure
– 3. Purpose
File Name
File name is a string of characters that
make up a valid filename for the operating
system. It may contain two parts, a
primary name and an optional period with
the extension.
Example:
– input.data
– store
– Student.c
– Text.out
Data Structure
Data structure of a file is defined as FILE
in the library of standard I/O function
Declares the variable fp
definitions.
as a “pointer to the data
Generaltype
format
FILE”.for declaring and opening a
file:
FILE *fp;
fp = fopen(“filename”, “mode”);

FILE is a structure
that is defined in the Note that both the
I/O library filename and mode are
specified as strings
The Mode to Specify the Purpose
of Opening This File:
r open the file for reading only.
w open the file for writing only.
a open the file for appending (or adding)
data to it.
When trying to open a file, one of
the following things may happen:
1. When the mode is ‘writing’, a file with the
specified name is created if the file does not
exist. The contents are deleted, if the file
already exists.
2. When the purpose is ‘appending’, the file is
opened with the current contents safe. A file
with the specified name is created if the file
does not exist.
3. If the purpose is ‘reading’, and if it exists,
then the file is opened with the current
contents safe otherwise an error occurs.
Example
FILE *p1, *p2;
p1 = fopen(“data”, “r”);
p2 = fopen(“results”, “w”);
If results already exists, its contents are
deleted and the file is opened as a new
file.
If data file does not exist an error will
occur.
Additional Modes of Operation
* r+ The existing file is opened to the
beginning for both reading and writing.
* w+ Same as w except both for reading and
writing
* a+ Same as a except both for reading and
writing.

Note :We can open and use a number of


files at a time. This number however
depends on the system we use.
12.3 Closing a File
A file must be closed as soon as all
operations on it have been completed.
Why closing a file?
– 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 mode.
Format of Closing a File
fclose (file_pointer);
Example

FILE *p1,*p2;
p1 = fopen(“INPUT”, “w”);
p2 = fopen(“OUTPUT”, ‘r’);

fclose(p1);
fclose(p2);

Note
Once a file is closed, its file pointer can be
reused for another file.
A a matter of fact all files are closed
automatically whenever a program
terminates.
However, closing a file as soon as you are
done with it is a good programming habit.
12.4 I/O Operations on Files Ⅰ
getc and putc fuctions
The simplest file I/O functions are getc and
putc, which are analogous to getchar and putchar
functions and handle one character at a time.
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
c = getc(fp2); would read a character from the
file whose file pointer is fp2.
Example 12.1
Write a program to read data from the
keyboard, write it to a file called INPUT,
again read the same data from the INPUT
file, and display it on the screen.
main(){
File *f1;
char c;
printf(“Data Input \n\n”);
/* open the file INPUT*/
f1 = fopen(“Input”, “w”);
/*get a character form keyboard*/
while((c=getchar()) != EOF){
/*write a character to input*/
putc(c,f1);
}
/*close the file*/
fclose(f1);
printf(“\n Data Output\n\n”);
/*open the file input*/
Data f1
INPUT
= fopen(“INPUT”, “r”);
This /*ead
is a a character
program to from
testINPUT*/
while((c=getc(f1)) != EOF){
the file handling
features on the system
/*display ^Z
a character on
screen*/
printf(“%c”,c);
Data }Output
This /*close
ia a the fileto
program
fclose(f1);
INPUT*/
test the file handling
features
} on the system
12.4 I/O Operations on Files Ⅱ
getw and putw fuctions
The getw and putw are integer-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 12.2
A file named DATA contains a series of
integer numbers. Code a program to read
these numbers and then write all ‘odd’
numbers to a file to be called ODD and all
‘even’ numbers to a file to called EVEN.
#inlude <stdio.h>
main(){
FILE *f1, *f2, *f3;
int number, i;
printf(“Contents of DATA file /n/n”);
f1 = fopen(“DATA”, “w”);
for(i=1;i<=30;i++){
scanf(“%d”, &number);
if(number == -1) break;
putw(number, f1);
}
f1.fclose();
f1 = fopen(“DATA”, “r”);
f2 = fopen(“ODD”, “w”);
f3 = fopen(“EVEN”, “w”);
while((number=getw(f1)) != EOF){
if(number%2 == 0)
putw(number, f3);
else
putw(number,f2);
}
f1.fclose();
f2.fclose();
f3.fclose();
f2 = fopen(“ODD”, “r”);
f3 = fopen(“EVEN”, “r”);
printf(“\n\n Contents of ODD file\n\n”);
while((number=getw(f2)) != EOF)
printf(“%4d”, number);
while((number=getw(f3)) != EOF)
printf(“%4d”, number);
f2.fclose();
f3.fclose();
Output
Contents of DATA file
111 222 333 444 555 666 777 888 -1
Contents of ODD file
111 333 555 777
Contents of Even file
222 444 666 888
12.4 I/O Operations on Files

fprintf and fscanf fuctions
fprintf and fscanf can handle a group of
mixed data simultaneously.
The functions fprintf and fscanf perform
I/O operations that are identical to the
familiar printf and scanf functions, except
of course that they work on files.
The General Form of fprintf
fprintf(fp, “control string”, list);

fp is a file pointer associated with a file


that has been opened for writing.
The “control string” contains output
specifications for the items it the list.
The list may include variables, constants
and strings.
Example

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


The General Format of fscanf
fscanf(fp, “control string”, list);

This statement would cause the reading of


the items in the list from the file specified
by fp, according to the specifications
contained in the control string.
Example:

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


Example 12.3
Write a program to open a file named
INVENTORY and store in it the following
data:
Item name Number Price Quantity
AAA-1 111 17.50 115
BBB-2 125 36.00 75
C-3 247 31.75 104
Extend the program to read this data from
the file INVENTORY and display the
inventory table with the value of each item.
#include <stdio.h>
main(){
FILE *p;
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(“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++){
fscanf(fp, “%s %d %f %d”,
item,&number,&price,&quantity);
value = price*quantity;
Output fprintf(stdout, “%-8f %7d %8.2f %11.2f\n”,
Input
item, file name
number,price,quantity,value);
INVENTORY
}
Input fclose(fp);
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
12.5 Error Handling During I/O
Operations
Typical error situations include:
1. Trying to read beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file, When
the file is opened for another type of
operation.
5. Opening a file with an invalid filename.
6. Attempting to write to a write-protected file.
feof() & ferror()
feof() used to test for an end of file condition.
if(feof(fp))
printf(“End of data.\n”);
ferror() reports the status of file indicated.
if(ferror(fp)!=0)
printf(“An error has occurred.\n”);

fopen() tells whenever a file is opened.


if(fopen(fp) ==NULL)
printf(“File could not be opened.\n”);
Example 12.4
Write a program to illustrate error handling
in file operations.
#include <stdio.h>
main(){
char *filename;
FILE *fp1, *fp2;
int i, number;
fp1 = fopen(“TEST”, “w”);
for(i=10;i<=100;i++)
putw(i,fp1);
printf(“\nInput Filename\n”);
open_file: scanf(“%s”, filename);
if((fp1=fopen(filename, “r”))==NULL){
printf(“Cannot open the file./n”);
printf(“Type filename again.”);
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
60
70
80
90
100
Run out of data
12.6 Random Access to Files
Access only a particular part of a file and
not read the other parts, the functions are:
– ftell() takes a file pointer and return a number of
type long, that corresponds to the current
position.
– rewind() takes a file pointer and resets the
position to the start of the file.
Example
rewind(fp); Assign 0 to n because the file
n = ftell(fp); position has been set to the start
of the file be rewind.
fseek()
fseek function is used to move the file
position to a desired location within the file.
Example:
– fseek( file_ptr, offset, position);
– file_ptr is a pointer to the file concerned.
– offset is a number or variable of type long. It
specifies the number of position(bytes) to be
moved from the location specified by position.
– position is n integer number, and can take one of
the following three values:
0 Beginning of file
1 Current position
2 End of file
Operations of fseek Function
Statement Meaning
fseek(fp,0L,0); Go to the beginning.
(Similar to rewind)
fseek(fp,0L1); Stay at the current position.
(Rarely used)
fseek(fp,0L,2); Go to the end of file, pat the last
character of the file.
fseek(fp,m,0); Move to (m+1)th byte in the file
fseek(fp,m,1) Go forward be m bytes.
fseek(fp,-m,1); Go backward be m bytes from the current
position.
fseek(fp,-m,2); Go backward be m bytes from the end.
(Position the file to the mth character form
the end.)
Example 12.5
Write a program that uses the functions
ftell and fseek.
#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 = %1d\n”, ftell(fp));
fcolse(fp);
fp = fopen(“RANDOM”, “r”);
n = 0L;
while(feof(fp) == 0){
fseek(fp, n, 0);
printf(“Position of %c is %1d\n”, getc(fp),
ftell(fp));
n = n + 5L;
}
putchar(‘\n’);
fseek(fp, -1L, 2);
do{
putchar(getc(fp));
} while(!fseek(fp,-2L,1));
fclose(fp);
}
Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ
No. of characters entered = 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
Position of is 30
ZYXWVUTSRQPONMLKJIHGFEDCBA
Example 12.6
Write a program to append additional items
to the file INVENTORY created in Example
12.3 and print the total contents of the
file.
#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(invent_record *x, file *y);
printf(“Type filename”);
scanf(“%s”, filename);
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);
fclose(fp);
fp = fopen(filename, “r”);
12.6 Random Access to Files
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”,itme.name, item.number, item.price,
item.quantity);
}
fclose(fp);
}
void append(struct invent_record *product, File *ptr){
printf(“Item name:”);
scanf(“%s”, prodcut->name);
printf(“Item number:”);
scanf(“%s”, &prodcut->number);
printf(“Item price:”);
scanf(“%s”, &prodcut-> price);
printf(“Item quantity:”);
scanf(“%s”, &prodcut-> quantity);
fprintf(ptr, “%s %d %.2f %d”, product->name,
product->number, product->price,prodcut->quantity);
}
Output
12.6 Random Access to Files
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
12.7 Command Line Arguments
It is a parameter supplied to a program
when the program is invoked. This
parameter may represent a filename the
program should process.
Example
– execute a program to copy the contents of a
file named X_FILE to another one named
Y_FILE, then we may use a command line like
– C>PROGRAM X_FILE Y_FILE
argc & argv
In fact main can take two arguments called
argc and argv
– The variable argc is an argument counter that
counts the number of arguments on the
command line.
– The argv is an argument vector and represents
an array of character pointers that point to the
command line arguments. The size of this array
will be equal to the value of argc.
Example
argv[0] -> PROGRAM
argv[1] -> X_FILE
argv[2] -> Y_FILE
Example
main(int arge, char *argv[])
{
-------
-------
-------
}
The first parameter in the command line
always the program name and therefore
argv[0] always represents the program
name.
Example 12.7
Write a program that will receive a filename
and a line of text as command line arguments
and write the text to the file.
The command line is
F12_7 TEXT AAAAAA BBBBBB CCCCCC DDDDDD
EEEEEE FFFFFF GGGGGG
#include <stdio.h>
main(int arge, char *argv[]){
FILE *fp;
int i;
char word[15];
fp = fopen(arvg[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[i]*/
fclose(fp);
/*Writing content of the file to screen*/
printf(“Content 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 GGGGGG
No. of arguments in Command line=9
Contents of TEXT file
AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF
GGGGGG
C:/C/F12_7.EXE
TEXT
AAAAAAA
BBBBBB
CCCCCC
DDDDDD
EEEEEE
FFFFFF
GGGGGG

You might also like