0% found this document useful (0 votes)
36 views19 pages

Unit - V File Management

The document discusses file management in C programming. It explains what a file is and how to define, open, read, write and close files using functions like fopen, fclose, fread, fwrite. It also describes different modes like r, w, a, r+, w+, a+ for opening files and their purposes.

Uploaded by

ttramkumr
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
36 views19 pages

Unit - V File Management

The document discusses file management in C programming. It explains what a file is and how to define, open, read, write and close files using functions like fopen, fclose, fread, fwrite. It also describes different modes like r, w, a, r+, w+, a+ for opening files and their purposes.

Uploaded by

ttramkumr
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 19

JSV COLLEGE OF ARTS AND SCIENCE

AATTUKARAMPATTI, DHARMAPURI-9

C lass : I B.C.A. Staff : A.Menaka M.Sc.,B.Ed.,


Subject : Programming in “C” H.O.D : J. Ganesan M.CA., B.Ed.,

Unit – V File Management


Introduction:-
Q & A: Explain about File Management:-
 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
 This works fine as long as the data is small.
 Many real-life problems involve large volumes of data and in such situations; the console oriented
I/O operations pose 2 major problems.
 It becomes cumbersome and time consuming to handle large volumes of data
through terminals.
 The entire data is lost when either the program is terminated or the computer
is turned off.
 It is therefore necessary to have a more flexible approach where data can be stored on the disks
and read whenever necessary, without destroying the data.
 This method employs the concept of files to store data.
 A file is a place on the disk where a group of related data is stored.
 A file is a collection of records.
 A file is an external collection of related data treated as a unit.

 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:

Function Name Operation

fopen() Creates a new file for use & opens an existing file for use

fclose() Closes a file which has been operand for use

getc() Reads a character from a file

putc() Writes a character to a fi9le

fprintf() Writes a set of data values to a file

fscanf() Reads a set of data values to a file

getw() Reads an integer from a file

putw() Writes an integer from a file

fseek() Sets the position to a desired point in the file

ftells() Gives the current positions in the file (i.e., in terms of bytes from the start)

rewind() Sets the position to the beginning of the file.

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

 The function that prepares a file for processing is fopen.


 It does two things: First, it makes the connection between the physical file and the file stream in
the program.
 Second, it creates a program file structure to store the information needed to process the file.
C Program Buffer
#include<stdio.h> abcdefghijklmnopqrstu
void main () vwxyz
{
….}

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

Mode of Opening Purpose

R Open for reading

W Open for Writing (file need not exist)

A Open for appending (file need not exist

R+ Open for reading and writing, start at beginning

W+ Open for reading and writing (overwrite file)

A+ Open for reading and writing (append if file exist

 Many recent compiler include additional modes of operation. They include.


 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
“r” (read) mode:-
 The read mode (r) opens an existing file for reading. When a file is opened in this mode,
the file marker is positioned at the beginning of the file (first character). The file marker is a
logical element in the file structure that keeps track of our current position in the file.

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

“w” (write) mode:-


 The write mode (w) opens for writing. If the file doesn’t exist, it is created. IF it is already exists, it
is opened and all its data are erased; the file marker is positioned at the beginning of the file (first
character) It is an error to try to read from a file opened in write mode.
 Syntax :-
fp=fopen (“filename”,”w”);

“a” (append) mode:-


 The append mode (a) also opens an existing for writing. Instead of creating a new file, however,
the writing starts after the last character; that is new data is added, or appended, at the end of the
file.
 IF the file doesn’t exist, it is created and opened. In this case, the writing will start at the
beginning of the file; File opened in append mode are shown in
 Syntax :-
fp=fopen (“filename”,”a”);

“r+” (read and write) mode:-


 In this mode file is opened for both reading and writing the data. If a file does not exist then
NULL, is returned.
 Syntax :-
fp=fopen (“filename”,”r+”);
“w+” (read and write) mode:-
 In this mode file is opened for both writing and reading the data. If a file already exists its contents
erased. If a file does not exist then new file created.
 Syntax :-
fp=fopen (“filename”,”w+”);

“a+” (append and read) mode:-


 In this mode file is opened for reading the data as well as data can be added at the end.
Syntax:-
fp=fopen (“filename”,”a+”);
-5–
Closing a file:-
 A file must be closed as soon as all operations on it have been completed/
 In this mode file is opened for reading the data as well as data can be added at the end.
Syntax:-
fclose(file_pointer)
 Here file pointer indicates the pointer of the file
 Example:-
……………..
…………….
FILE * p1,*p2;
p1=fopen(“input”,”W”);
p2=fopen(“output”,”r”);
………………
………………
fclose(p1);
fclose(p2);
 Closing a file ensures that all outstanding information associated with the file is flushed out
from the buffers and all links to the file are broken.

 Another instance where we have to close a file is to reopen the same file in a different
mode.

 The I/O library supports the following function to do this:

 Where fp is the file pointer returned by the call to fopen ().

 fclose () returns 0 on success (or) -1 on error.

-6–
 Once a file is closed, its file pointer can be reused for another file.

Input and output operation on files:-


Q & A: What are the input and output operations used in Files?
 Once a file is opened, reading out of or writing to it is accomplished using the standard I/O
routines .
The getc():
 The simplest file I/O functions are getc and putc.
 These are analogous to getchar and putchar functions and handle one character at a time.
 Assume that a file is opened with mode w and file pointer fp1.
 Then the statement.

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

 Where c represents a character and fp represents a pointer to file.


 The file pointer moves by one character position for every operation of getc or putc.
The getw() and putw() function:

 The getw and putw are integer oriented functions.


 They are used to read and write integer values.
 Syntax:-

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.

Random Access to Files:-


Q & A: Describe about Random Access to files with Example?
 We can access the file in randomly by using the following function.
 When we are interested in accessing only a particular part of a file and not in reading the other
parts.
 This can be achieved with the help of the functions fseek, ftell, and rewind available in the
I/O library.
fseek():-
 Takes a file pointer and return a number of types long that corresponds to the current position.
 This function is useful in saving the current position of a file, which can be used later in
the program.
 It take the following form
 fseek(fp,offset,position);
 fp  pointer to FILE type
 Offset  number of bytes
 Position  it takes 3 values 0,1,2
rewind ():-
 Takes a file pointer and resets the position to the start of the file. for example, the statement
 rewind(fp);

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

Additional preprocessor directive are:-

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

Simple macro substitution:-


 It is used commonly to define constants.

- 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

Stringizing Operator #:-


 ANSI C provides an operator # called Stringizing operator to be used in the definition of
macro functions.
- 17 –
 This operator allows a formal argument within a macro definition to be converted to a
string.
Example:-
#define sum(xy) printf(#xy “=%f\n”,xy
main()
{
……………….
……………….
sum(a+b);
…………………
}
The preprocessor will convert the line
Sum (a+b);
into printf(“a+b”, “=%f\n”, a+b);
which is equivalent to printf(“a+b =%f\n”, a+b);
Token pasting Operator # #:-
 The token pasting operator ## defined by ANSI standard enables us to combine two tokens
within a macro definition to form a single token.
 #define combine(s1,s2) s1 ##s2
main()
{
………………….
………………….
printf(“%f”, combine(total, sales);
…………………….
…………………….
}
The preprocessor transforms the statement
printf(“%f”, combine(total, sales));
into the statement
printf(“%f”, totalsales);

- 18 –
*************Unit – V Completed******************

- 19 –

You might also like