Unit - V File Management
Unit - V File Management
AATTUKARAMPATTI, DHARMAPURI-9
The primary purpose of a file is to keep record of data. Record is a group of related fields. Field
is a group of characters they convey meaning.
Files are stored in auxiliary or secondary storage devices. The two common forms of secondary
storage are disk (hard disk, CD and DVD) and tape.
Each file ends with an end of file (EOF) at a specified byte number, recorded in file
structure.
A file must first be opened properly before it can be accessed for reading or writing.
When a file is opened an object (buffer) is created and a stream is associated with the object.
-1–
Using file can overcome these kinds of problems.
A file is a place on the disk where a group of related data is stored. C supports the basic file
operations such as
Naming a file
Opening a file
Reading data from a file
Writing data from a file
Closing a file
There are two distinct ways to perform file operations in C.
The first one is known as the low-level I/O and uses UNIX system calls.
The second method is referred to as the high-level I/O operations and uses functions in “C”
standard I/O library.
The high level I/O functions are:
fopen() Creates a new file for use & opens an existing file for use
ftells() Gives the current positions in the file (i.e., in terms of bytes from the start)
-2–
Defining and opening a File:-
Q & A: How will you open and close a file?
To store data in a file in the secondary memory, then certain things about the file should be
specified to the operating system. They include.
File name
Data structure
Purpose
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.
Examples
1. Input.data
2. Store
3. PROG.C
4. Student.c
5. Text.out
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.
General Format
FILE * Fp;
Fp=fopen(“filename”, “mode”);
Stream
File Structure abcdefghijklmnopqrstu
vwxyz
199 10212 10200 … …
1 2 3 ..
1 2 3
-3–
The first statement declares the variable fp as a “pointer to the data type FILE.
FILE is a structure that is defined in the I/O library.
The second statement opens the filename and assigns an identifier to the FILE type pointer fp.
A valid file name must be given.
File Mode:-
When we open a file, we explicitly define its mode. The mode shows how we will use the
file: for reading, for writing, or for appending.
R Opens the file for reading only
W Opens the file for writing only.
A Opens the file for adding data to it.
Exam,ple File * P1, P2;
P1= fopen(“data”,”r”);
P2=foen(“resul”.”w”);
-4–
The file must already exist: if it does not, NULL is returned as an error. Files opened for
reading are shown in Figure 6.4. If we try to write a file opened in read mode, we get an error
message.
Syntax :-
fp=fopen (“filename”,”r”);
Another instance where we have to close a file is to reopen the same file in a different
mode.
-6–
Once a file is closed, its file pointer can be reused for another file.
putc(c,fp1)
It is used to read a character from a file associated with FILE pointer fp1. Similarly getc is
used to read the data from file that has been opened in read mode.
Syntax:-
c=getc(fp);
Where c represents a variable of character and fp represents a pointer to file.
-7–
Program: To count the number of lines, words, and characters in a file
# #include<stdio.h> {
#include<conio.h> if(ch=='')
void main() W ++;
{ else if(ch=='\n' || ch='\0')
FILE *fp; {
char name[100],ch; l++
int c=0, w=0, l=0; w++;
clrscr(); }
printf("Enter line of text:\n"); else
fp=fopen("Unit-I Overview c.txt","w"); c++;
scanf("%[^EOF]",name); }
fprintf(fp,"%s",name); fclose(fp);
fclose(fp); printf("no of character:%d\n no of words: %d\n
fp=fopen("Unit-I Overview c.txt","r"); no of lines:%d\n",c,w,l);
while((ch=getc(fp))!=EOF) getch();
}
Putc():-
It is used to write a character to the file.
Syntax:-
put (c,fp);
getw(fp);
putw(integer, fp);
fscanf():
fscanf allows to read multiple data items which may (or not) be of different types to a file.
fscang() is similar to scanf()
Syntax:-
o fscanf(“Control string”, argument-list);
-8–
Program: To count the number of lines, words, and characters in a file
# #include<stdio.h> if(temp%2==0)
#include<conio.h> putw(temp,f3);
void main() else
{ putw(temp,f2);
FILE *f1,*f2,*fe; }
int temp, I; fclose(f1);
clrscr(); fclose(f2);
printf(“Enter number:\n”); fclose(f3);
f1=fopen(“input.txt”,”w”); f2=open(“odd.txt”,”r”);
for(i=0;i<=50;i++) f3=open(“even.txt”,”r”);
{ printf(“\nodd number are \n”);
scanf(“%d”,&temp); while((temp=getw(f2))!=EOF)
if(temp= = -1)break; printf(“%d”,temp);
putw(temp,f1); printf(“\nEven number are \n”);
} while(temp=getw(f3))!=EOF)
fclose(f1); printf(“%d”,temp);
f1=fopen (“input.txt”,” “r”); fclose(f2);
f2=fopen(“odd.txt”,””w”); fclose(f3);
f3=fopen(“even.txt”,”w”); getch();
while((temp=getw(f1))!=EOF) }
{
fprintf():
fprintf is to write multiple data items which may (or not) be of different types to a file. fprintf() is
similar to printf()
Syntax:-
o fprintf(“Control string”, argument-list);
Error Handling During I/O Operations:-
Q & A : Explain about Error Handling During I/O Operations?
It is possible that an error may occur during I/O operations on a file.
o Trying to read beyond the end-of file mark
o Device overflow
o File has not been opened
o Opening a file with an invalid filename.
o Trying to perform an operation on a file, when the file is opened for
another type of operation.
o Attempting to write to a write-protected file.
-9–
They are two status-inquiry library functions; feof and ferror that can help us detect I/O error in
the files.
Example 1 :
if(feof(fp))
printf(“End of data.\n”);
Example 2:
If(feeor(fp)!=0)
printf(“An error has occurred”);
Would print the error message, if the reading is not successful.
If the file cannot be opened for some reason then the function returns a null pointer.
This facility can be used to test whether a file has been opened or not.
- 10 –
Operation of fseek ( ) function:-
Statement Meaning
fseek(fp,01,0); Go to the beginning
fseek(fp,01,1); Stay at the current position
fseek(fp,01,2); Go to the end of the file, pas the last character of the file.
fseek(fp,m,0); Move the(m+1)th byte in the file
fseek(fp,m,1); Go forward by m bytes
fseek(fp,-m1); Go backward by m bytes from the current position
fseek(fp,-m,2); Go backward by m bytes from the end.
ftell( ):-
The function ftell() returns the current position of the file pointer.
syntax:-
o position = ftell(fp);
Here fp is a pointer to FILE type representing a file, the current position of the file pointer
of the file is returned by the function.
Command Line arguments:-
Q & A Explain about command and Line arguments with example?
It is a parameter supplied to a program when the program is invoked.
This parameter may represent a filename the program should process.
Example:-
c>PROGRAM X_FILE
Consider the first line of the main function i.e., main(). These parentheses may contain special
arguments that allow parameters to be passed to main from the Operating System. Two such
arguments are argc and argv, respectively.
The first of these, argc, must be an integer variable, while the second, argv, is an array of
pointer to character, ie., an array of strings. Each string in this array will represent a parameter that
is passed to main.
The value of argc will indicate the number of parameters passed.
The variable argc is an argument counters that counts they number of arguments on the
command line.
- 11 –
The argy is an argument vector and represents an array of character pointer that points to
the command line arguments.
argv[0] program
argv[1] X_FILE
argv[2] Y_FILE
#include<stdio.h> while(!feof(fin))
#include<process.h> {
void main(int argc, char*argv[]); c=getc(fin);
{ putc(c,fout);
FILE *fin,*fout; }
char c; fclose(fin);
If(argc!=3) fclose(fout);
{ }
printf(“Invalid number of
arguments”); Output:-
exit(1); c:\> copy om dat om1.dat
} As a result the contents of om.dat are
fout=fopen(argv[2].”W”); copied to om1.dat
fin(fopen(argv[1],”r”);
The preprocessor:-
Q &A: Discuss about preprocessor in Detail:-
We have already seen features such as structures and pointers.
The unique feature of the C language is the preprocessor.
The C preprocessor provides several tools that are unavailable in other high-level language.
The programmer can use these tools to make his program easy to read, easy to modify,
portable and more efficient.
Preprocessor is a collection of special statements, called directives, which are executed at
the beginning of the compilation process.
The # include and # define statements are the best example3s of preprocessor directives.
Directive Function
# if, Test a compile time condition
# else, Specifies alternatives when # if test fails
# endif, Specifies the end of # if
# infndef, Tests whether macro is defined
# define Defines a macro substitution
# undef Undefines a macro - 12 –
Preprocessor directives usually appear at the beginning of a program though this is not a
frim requirement.
Thus, a preprocessor directive may appear anywhere within a program. However, the
direct5ive will a program.
However, the directive will apply to the portiuon of the program following its appearance.
The # if, #elseif, #else and #endif directives are used most frequently.
They permit conditional compilation of the source program, depending on the value of one
or more try/false conditions.
They are some times used in conjunction with the defined operator, which is used to
determine whether or not a symbol constant or a macro identifier has been defined within a
program.
These directives are divided into three categories:-
Macro substitution directive
File inclusion directives.
Nested macro substitution.
Macro Substitution:-
Q & A: Give short notes on Macro substitution?
It is a process where an identifier in a program is replaces by a predefined string composed
of one or more tokens.
The preprocessor accomplished this task under the direction of #define statements.
This statement usually known as macro definition.
Syntax:-
#define
#defineidentifier
identifier
string.
string.
There are different forms of macro substitution. The most common forms are:-
o Simple macro substitution
o Argumented macro substitution
o Nested macro substitution
- 13 –
Syntax:-
#define
#defineidentifier
identifier
Example:- string.
string.
# define pi 3.14
# define false 0
Macro with arguments:-
The preprocessor allows defining more complex and more useful form of replacements.
When a macro is called the preprocessor substitutes the string, replacing, the formal
parameter with the actual parameters.
Syntax:-
#define
#define
Example:- identifier(f1,f2,f3……..fn)string
identifier(f1,f2,f3……..fn)string
# # define cube(x) (X* X* X)
Nesting of macros:-
One macro in the definition of another macro. That is macro definitions may be nested.
Example:1
#define m 5
#define n m+1
Example : 2
#define square(x) ((x) * (x))
#define cube(x) (square(x) * (x))
#define sixth (cube (x) * cube(x))
File Inclusion:-
Q & A :Write a note on File inclusion?
An external file containing functions or macro definitions can be included as a part so that
we need not rewrite those functions or macro definitions.
This is achieved by the preprocessor directive
Syntax:-
#include<filename>
#include<filename>
Where filename is the name of the file containing the required definitions or functions.
Example:-
SYNTAX.C Contains syntax definitions
STAT.C Contains statistical functions
TEST.C Contains test functions
Compiler control Directives:-
- 14 –
Q & A: Discuss about compiler control directives?
While developing large programs there are many problems to be faced. They are as
follows.
Problem 1 : Whether a macro is defined in file or not is not known
Problem 2 : Whether the program is portable
Problem 3 : Whether the program will accept additional features or not.
Problem 4 : Whether the debugging statements are a part of the program and should become
active only when needed.
Solutions for the problem are provided below:-
Problem 1:-
This situation refers to the conditional definitions of a macro. Macro test is defined to
check whether it is defined in the header file or not. This is done as follows.
#include “DEFINE.H”
#indef TEST
#define TEST 1
#endif
Problem 2:-
This is make the program portable. This is done as follows.
------------------------------ ------------------------------
----------------------------- -----------------------------
Main() Main()
{ {
------------------------------ ------------------------------
----------------------------- -----------------------------
# ifdef IBM_PC # ifdef IBM_PC
------------------------------ ------------------------------
----------------------------- -----------------------------
} }
In order to run on IBM PC we include the directive # define IBM _PC.
The compiler compiles the code for IBM pc if IBM_PC is defined or the code for the HP
machine if it is not
Problem 3-
The control directive take the following form
#ifdef abc groupAlines
- 15 –
#else groupB lines
#end if
GroupA lines are included if the customer ABC is defined. Otherwise group B are included
Problem 4-
Debugging and testing are done to detect errors in the program.
The debugging statements are not required once the errors are isolated and corrected. We
can either delete all of them or alternately make them inactive using control directives
#if Constant
Expression
{
Statements 1;
Statements 2;
}
Examples:- #endif
-----------------
#ifdef Test
{
printf(“array elements\n”);
for(i=0;i<m;i++)
printf(“x[%d]=%d\n”,I,x[i]);
}
#endif
--------------------
#ifdef TEST
Printf(………..);
#endif
--------------------
If the result of the constant-expression in nonzero (true) then all the statement between the #if and
#endif are included for processing; otherwise they are skipped.
ANSI ADDITION:-
ANSI committee has added some more preprocessor directives to the existing list.
#elif Provides alternative test facility
#pragma specifies certain instructions
#error Stops compilation when an error occurs.
- 16 –
The ANSI standard also includes two new preprocessor operations.
# Stringizing operator
## Token-pasting operator.
#elif Directive:-
The #elif enables us to establish an “if…else…if..” sequence for testing multiple
conditions.
The general from of use of #elif if
# if expression 1
Statement sequences 1
#elif expression 2
Statement sequences 2
………………………..
……………………….
#elif expression N
Statement sequence N
#endif
#pragma Directive:-
The #pragma is an implementation oriented directive that allows us to specify various
instructions to be given to the complier. It takes the following form
#pragma name
Where, name is the name of the pragma we want. For example, under Microsoft C
#pragma loop_opt (on)
#error Directive:-
The #error Directive is used to produce diagnostic messages during debugging.
#error error message
Where, the #error directive is encountered, it displays the error message and terminates processing
#if !defined(FILE_G)
#error NO GRAPHICS FACILITY
#endif
- 18 –
*************Unit – V Completed******************
- 19 –