0% found this document useful (0 votes)
6 views43 pages

Unit5 231CSC201T

The document provides an overview of file operations in C programming, including definitions, types of files (text and binary), and basic file operations such as opening, reading, writing, and closing files. It also details various file input/output functions, their syntax, and examples, along with the differences between similar functions. Additionally, it discusses the types of file processing: sequential and random access.
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)
6 views43 pages

Unit5 231CSC201T

The document provides an overview of file operations in C programming, including definitions, types of files (text and binary), and basic file operations such as opening, reading, writing, and closing files. It also details various file input/output functions, their syntax, and examples, along with the differences between similar functions. Additionally, it discusses the types of file processing: sequential and random access.
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/ 43

1

UNIT 5
Introduction – Using files in C - File operation: Read data from files, writing data to
files, detecting the end of file, Functions for selecting a record randomly – File pointer –
Error handling - Types of file processing: Sequential access, Random access- Dynamic
memory allocation.

FILES
Files are very important for storing information’s permanently. In other words files
are storage device which is used to store data permanently. File stores information for many
purposes and retrieve whenever required by our programs.

DEFINITION:
File is defined as a set of records containing numbers, symbols and text that can be
accessed through various file functions.

TYPES:
There are Many files which have their own type and own names. When we store a
file in the system, then we must specify the name and the type of file. The name of file will
be any valid name and type means the application with the file has linked. Based on this
we have two types:
1. Text File
2. Binary File

Text File:
 Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
 When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.
 They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.
 Extension – “ filename.txt “

Binary File:
 Binary files are mostly the .bin files in your computer.
 Instead of storing data in plain text, they store it in the binary form (0's and 1's).
 They can hold higher amount of data, are not readable easily and provides a better
security than text files.
 Extension – “ filename.dat “

NEED FOR FILE:


 When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
2

 If you have to enter a large number of data, it will take a lot of time to enter them
all. However, if you have a file containing all the data, you can easily access the
contents of the file using few commands in C.
 You can easily move your data from one computer to another without any changes.

BASIC FILE OPERATIONS:


 Defining a file
 Opening a file
 Reading and writing a file
 Closing a file

Defining a file:
When accessing files through C, the first necessity is to have a way to access the files.
For C language we use a FILE pointer, which will let the program keep track of the file
being accessed.
Syntax: FILE *filepointer;
Example: FILE *fp;
This declaration is the communication between the file and the program. Here file is a
data structure; it has information about the file.

Opening a file:
Before we perform any operations on a file, we need to open it. We do this by using a
file pointer, then you use the function fopen() for opening a file.
Syntax : filepointer = fopen(“filename”.”mode”);
Example : fp = fopen(“cse.txt”,”r”);

File opening modes:


The mode specifies the purpose of opening the file. Mode can be of following types,
any one of the following mode can be used in the program.
Purpose
S.No Mode Meaning File is not
File is exist
exist
1 r Reading Open the file for reading only. NULL
Writing Open the file for over writing on Create new file
2 w
existing content.
Appending Open the file for appending (or Create new file
3 a
adding) data to it.
Reading+ New data is written at the beginning Create new file
4 r+
Writing override existing data.
Writing+ Override existing data. Create new file
5 w+
Reading
3

Reading+ The new data is appended at the end Create new file
6 a+
Appending of file.

Closing a file:
A file must be close after completion of all operation related to the file. For closing
file we need to use the fclose() function.
Syntax: fclose(filepointer);
Example: fclose(fp);

Program for opening and closing a file :


Method 1:
#include <stdio.h>
void main ()
{
FILE *fp;
fp = fopen("cse.txt", "r");
if (fp == NULL)
{
printf(" File does not exist ");
exit(0);
}
fclose(fp);
}

Method 2 :
#include <stdio.h>
void main ()
{
char filename[50];
FILE *fp;
printf(“ enter the filename “);
gets(filename);
fp = fopen("filename", "r");
if (fp == NULL)
{
printf(" File does not exist ");
exit(0);
}
fclose(fp);
}

FILE INPUT AND OUTPUT FUNCTIONS


4

Unformatted input and output file functions for text file:

1.getc():
It is used to read a single character from both console screen and file at a time.Reads
the next character from the given input stream. getc() may be implemented as a macro.
Syntax: 1. variable=getc(stdin);
2. variable =getc(filepointer);
Example: 1. ch=getc(stdin);
2. ch=getc(fp);
EXAMPLE:
//Read content from file and display in console screen
#include<stdio.h>
#include<stdlib.h>
void main()
{
char ch;
FILE *fp;
fp=fopen(“cse.txt”,”r”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf((“\nContents from file are:”);
while((ch=getc(fp))!=EOF)
{
putchar(ch);
}
fclose(fp);
}
OUTPUT:
Contents from file are:Hello World
5

2.fgetc():
It is used to read the next character from the file. It is similar to getc() except it is
specific to file access.
Syntax: variable=fgetc(filepointer);
Example: ch=fgetc(fp);

EXAMPLE:
//Read content from file and display in console screen
#include<stdio.h>
#include<stdlib.h>
void main()
{
char ch;
FILE *fp;
fp=fopen(“cse.txt”,”r”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf((“\nContents from file are:”);
while((ch=fgetc(fp))!=EOF)
{
putchar(ch);
}
fclose(fp);
}

OUTPUT:
Contents from file are:Hello World
6

Difference between getc() and fgetc():


getc() fgetc()

* It is used to read a single character from *It is used to read the next character from
both console screen and file at a time. the file. It is similar to getc() except it is
specific to file access.
*Reads the next character from the given * Reads the next character from the given
input stream. input stream

* getc() may be implemented as a macro. *f getc() may not be implemented as a


macro.
* Syntax: 1. variable=getc(stdin);
2. variable=getc(filepointer); * Syntax: variable=fgetc(filepointer);

*Example: 1. ch=getc(stdin);
2. ch=getc(fp); *Example: ch=fgetc(fp);

3.putc():
putc() is used to write a single character to a file. It writes a character to the given
output stream. putc() may be implemented as a macro. It takes two arguments.
Syntax: putc(variable,filepointer);
Example: putc(ch,fp);

EXAMPLE:
//Read from screen and write in file.
#include<stdio.h>
#include<stdlib.h>
void main()
{
char ch;
FILE *fp;
fp=fopen(“cse.txt”,”r”);
if(fp==NULL)
7

{
printf(“Can’t open”);
exit(0);
}
printf((“\nEnter the text”);
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
fclose(fp);
}
OUTPUT:
Enter the text: Good Morning!!!

4.fputc():
This performs the same operation of putc() function. It writes a character to the
given output stream. But fputc() cannot be implemented as a macro. It takes one argument.
Syntax: fputc(variable,filepointer);
Example: fputc(ch,fp);

EXAMPLE:
//Read from screen and write in file.
#include<stdio.h>
#include<stdlib.h>
void main()
{
char ch;
FILE *fp;
fp=fopen(“cse.txt”,”r”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf((“\nEnter the text”);
8

ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp);
ch=getchar();
}
fclose(fp);
}
OUTPUT:
Enter the text: Good Morning!!!

Difference between putc() and fputc():


putc() fputc()
* putc() is used to write a single character * This performs the same operation of
to a file. putc() function.
*It writes a character to the given output *It writes a character to the given output
stream. stream.
* putc() may be implemented as a macro. *But fputc() cannot be implemented as a
macro.
*Syntax: putc(variable,filepointer); *Syntax: fputc(variable,filepointer);

*Example: putc(ch,fp); *Example: fputc(ch,fp);

5.fgets():
fgets() is a file input statement which is used to read a string from the file. It takes
three arguments.
Syntax: fgets(stringvar,length,filepointer);
Here the stringvariable is the variable declared to hold a string. Length is the size of the
string.
Example: fgets(a,100,fp);

6.fputs:
fputs() is a file output statement that is used to write a string to the file. It takes two
arguments.
Syntax: fputs(stringvar,filepointer);
9

Example: fputs(a,fp);

EXAMPLE for fgets() and fputs():


//Copy from one file to another
#include<stdio.h>
#include<stdlib.h>
void main()
{
char ch[10];
FILE *fp,*fp1;
fp=fopen(“cse.txt”,”r”);
fp1=fopen(“name.txt”,”w”);
if(fp==NULL||fp1==NULL)
{
printf(“Can’t open”);
exit(0);
}
while(fp!=EOF)
{
fgets(ch,10,fp);
fputs(ch,fp1);
}
fcloseall();
}

OUTPUT:
“cse.txt”:
Computer Science and Engineering
Civil Engineering
Mechanical Engineering

“name.txt”:
Computer Science and Engineering
Civil Engineering
Mechanical Engineering
10

7. getw():
This is one of the file input/output functions. The getw() function is used to read an
integer from a file pointedby file pointer and assigns the value to the variable. It takes one
argument.
Syntax: variable=getw(filepointer);
Example: ch=getw(fp);

8. putw():
This is also one of file input/output functions. The putw() function is used towrite
an integer value into the file. It takes two arguments.
Syntax: putw(variable,filepointer);
Example: putw(ch,fp);

EXAMPLE for getw() and putw():


//Copy integers from one file to another
#include<stdio.h>
#include<stdlib.h>
void main()
{
int regno;
FILE *fp,*fp1;
fp=fopen(“cse.txt”,”r”);
fp1=fopen(“regno.txt”,”w”);
if(fp==NULL||fp1==NULL)
{
printf(“Can’t open”);
exit(0);
}
while(!feof(fp))
{
regno=getw(fp);
putw(regno,fp1);
}
fcloseall();
11

OUTPUT:
“cse.txt”:
1001
1005
1013
“regno.txt”:
1001
1005
1013

BINARY FILES:
1.fread():
This function is used to read upto count objects into the array buffer from the given
input stream (i.e.)it is used for reading an entire block from a given binary file. It is an
formatted read function.
Syntax: fread(&buffer_ptr,size,count,fileptr);
Example: fread(&s,n,2,fp);

2.fwrite():
The fwrite() function is used to write the objects in the given buffer to the output
stream (i.e.) it is used for writing an entire structure block to a binary file. It is an
unformatted write function.
Syntax: fwrite(&buffer_ptr,size,count,fileptr);
Example: fwrite(&s,n,1,fp);

EXAMPLE:
//Read from a binary file and copy it in another
#include<stdio.h>
#include<stdlib.h>
struct student
{
int rollno;
char name[20];
12

}
void main()
{
FILE *fp1,*fp2;
int i,n=5;
fp=fopen(“in.dat”,”rb”);
fp1=fopen(“out.dat”,”w”);
if(fp1==NULL||fp2==NULL)
{
printf(“Can’t open”);
exit(0);
}
for(i=0;i<n;i++)
{
fread(&s,sizeof(s),1,fp1);
}
for(i=0;i<n;i++)
{
fwrite(&s,sizeof(s),1,fp2);
}
fclose(fp1);
fclose(fp2);
}
OUTPUT:
“in.dat”:
1001 Abi
1002 Bharathi
“out.dat”:
1001 Abi
1005 Bharathi

Formatted input and output file functions

1.fscanf():
This is a formatted file input function. This is used to read formatted data from the
given file. It takes three arguments.
13

Syntax: fscanf(filepointer,”controlstring”,&var1,&var2,……,&varn);
Example: fscanf(fp,”%d%s,&rollno,&name);

EXAMPLE:
//Read from file and display in console screen
#include<stdio.h>
#include<stdlib.h>
void main()
{
char name[20];
int rollno;
FILE *fp;
fp=fopen(“file.txt”,”r”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf(“The contents are:”);
fscanf(fp,”%d%s”,&rollno,&name);
printf(“\n%d%s”,rollno,name);
fclose(fp);
}
OUTPUT:
The contents are: 1001 Raja

2.fprintf():
This function is used to write or print any formatted data to the file. fprintf() is a
formatted file output function. It takes three arguments.
Syntax: fprintf(filepointer,”controlstring”,var1,var2,……,varn);
Example: fprintf(fp,”%d%s,rollno,name);

EXAMPLE:
//Read from console and display in file
#include<stdio.h>
#include<stdlib.h>
void main()
14

{
char name[20];
int rollno;
FILE *fp;
fp=fopen(“file.txt”,”w”);
if(fp==NULL)
{
printf(“Can’t open”);
exit(0);
}
printf(“Enter rollno and name:”);
scanf(”%d%s”,&rollno,&name);
fprintf(fp“%d%s”,rollno,name);
fclose(fp);
}
OUTPUT:
Enter rollno and name: 1019 Bharathi
“file.txt”
1019 Bharathi

TYPES OF FILE PROCESSING: SEQUENTIAL ACCESS, RANDOM ACCESS

In computer programming, the two main types of file handling are:


 Sequential access.
 Random access.
15

SEQUENTIAL ACCESS FILES


Sequential files are generally used in cases where the program processes the data
in a sequential fashion – i.e. counting words in a text file – although in some cases, random
access can be feigned by moving backwards and forwards over a sequential file.

Description:

Sequential access files access the contents of the file in a sequential manner, (i.e.)
the file access pointer starts from the first character in the file and proceed until the last
character in the file (EOF).In order to access the nth character, all previous characters have
to be read and ignored. This method can be applicable for both text files and binary files.

Reading and Writing in sequential files:

The putc() and getc() functions are used to read and write a single character from text
files ,whereas read() and write() functions are used to read and write blocks of binary data.

Eg: (Student mark analysis)

# include<stdio.h>

#include<stdlib.h>
16

struct student

int roll_no;

char name[20];

int m1,m2,m3;

}s;

void main()

int i,n,key,ch,f;

FILE *fp;

printf(“how many records:”);

scanf(“%d”,&n);

fp=fopen(“stud.dat”,”wb”);

if(fp==NULL)

printf(“file can’t open”);

exit(0);

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

printf(“enter rollno,name,m1,m2,m3:”);

scanf(“%d%s%d%d%d”,&s.roll_no,&s.name,&s.m1,&s.m2,&s.m3);

fwrite(&s,sizeof(s),1,fp);
17

fclose(fp);

while(1)

printf(“1.display ,2.search ,3.exit:”);

printf(“enter your choice:”);

scanf(“%d”,&ch);

switch(ch)

case 1:fp=fopen(“stud.dat”,”rb”);

if(f1==NULL)

printf(“file can’t open”);

exit(0);

printf(“the records are:”)

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

fread(&s,sizeof(s),1,fp);

printf(“%d%s%d%d%d”,s.roll_no,s.name,s.m1,s.m2,s.m3);

fclose(fp);

break;
18

case 2:printf(“enter rollno to search:”);

scanf(“%d”,&key);

fp=fopen(“stud.dat”,”rb”);

if(fp==NULL)

printf(“file can’t open”);

exit(0);

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

fread(&s,sizeof(s),1,fp);

if(key==s.roll_no)

printf(“search successfull:”);

printf(“%d%s%d%d%d”,s.roll_no,s.name,s.m1,s.m2,s.m3);

f=1;

break;

if(f==0)

printf(“search failed:”);

}
19

break;

case 3:printf(“exit”);

exit(0);

default:printf(“enter correct choice:”);

break;

Uses:

*It is relatively simple when compared to random access.

*It is used for storing logs, ASCII, trace files etc....

EXAMPLE PROGRAM: FINDING AVERAGE OF NUMBERS STORED IN


SEQUENTIAL ACCESS FILE

#include<stdio.h>
void main()
{
FILE* fp;
int n[50], i = 0;
float sum = 0;
if ((fp = fopen("num.dat", "r")) != NULL)
{
puts("Reading numbers from num.dat");
while (!feof(fp))
{
fscanf(fp, "%d ", &n[i]);
printf("%d %d\n", i, n[i]);
sum += n[i];
i++;
}
fclose(fp);
if (i > 0)
20

{
float average = sum / i;
printf("The average is %f for %d numbers\n", average, i);
}
else
{
puts("No data available in num.dat!");
}
}
else
{
printf("Unable to open num.dat...\n");
}
}

RANDOM ACCESS FILE


Random access file handling, however, only accesses the file at the point at which the data
should be read or written, rather than having to process it sequentially. A hybrid approach
is also possible whereby a part of the file is used for sequential access to locate something
in the random access portion of the file, in much the same way that a File Allocation Table
(FAT) works.

OTHER FILE HANDLING FUNCTIONS (OR) RANDOM ACCESS


FUNCTIONS
Apart from the basic file functions in c we have few other functions that allow
the user to access the file in random manner. The programs that we have learned so far are
based on sequential access (i.e.) one by one or in linear fashion, but by using these functions
we can access it randomly. The random access functions are as follow:
 fseek()
 ftell()
 rewind()

fseek() - It is used to moves the reading control to different positions using fseek()
function.
ftell() - It tells the byte location of current position in file pointer.
rewind() - It moves the control to beginning of a file.

fseek() :
21

It is possible to move the reading control to different positions by using fseek()


function.
Syntax : The syntax for the fseek function in the C Language is:
fseek(Filepointer, offset, position/whence);
filepointer:
It is nothing but the file that we declare in the beginning of the program.
e.g : FILE *fp;
Here “ fp “ is the file pointer.
Offset :
The offset to used (in bytes) when determining the new file position.
Whence/position:
It can be one of the following values:

SEEK_SET The new file position will be the beginning of the file plus offset (in
bytes).
SEEK_CUR The new file position will be the current position plus offset (in bytes).
SEEK_END The new file position will be the end of the file plus offset (in bytes).

Example :
fseek(fp, 0, SEEK_SET); // go to the beginning of the file

fseek(fp, 10, SEEK_SET); // go 10 bytes from the starting of the file

fseek(fp, 2, SEEK_CUR); // advance 2 bytes from the current position

fseek(fp, -2, SEEK_CUR); // back up 2 bytes from the current position

fseek(fp, 0, SEEK_END); // go to the end of the file

fseek(fp, -10, SEEK_END); // back up 10 bytes from the end of the file

Returns :
The fseek function returns zero if successful. If an error occurs, the fseek function
will return a nonzero value.

Program :
22

#include <stdio.h>
void main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is ece department", fp);
fseek( fp, 7, SEEK_SET );
fputs(" cse department ", fp);
fclose(fp);
}

Let us compile and run the above program that will create a file file.txt with the following
content. Initially program creates the file and writes This is ece department but later we
had reset the write pointer at 7th position from the beginning and used puts() statement
which over-write the file with the following content “ cse department “
The final content in the file is
“ This is cse department “

ftell() :
In the C Programming Language, the ftell() function returns the current file
position indicated by the pointer in the program.

SYNTAX:
The syntax for the ftell function in the C Language is:
Variable = ftell(Filepointer);
Example : ch=ftell(fp)
The file pointer gives the current position from the beginning of the file.

RETURNS
The ftell() function returns the current file position indicator for filepointer. If
an error occurs, the ftell() function will return -1 and update error.
Program:

#include <stdio.h>
#include<stdlib.h>
23

void main ()
{
FILE *fp;
int length;
fp = fopen("file.txt", "r");
if( fp == NULL )
{
printf("cnat open");
exit(0);
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);

printf("Total size of file.txt = %d bytes\n", length);


}

Let us assume we have a text file file.txt, which has the following content
This is cse department
Now let us compile and run the above program that will produce the following result if
file has above mentioned content otherwise it will give different result based on the file
content
Output :
Total size of file.txt = 23 bytes

Rewind() :
In the C Programming Language, the rewind() function sets the file position to
the beginning of the file for the current position of the file pointer. It also clears the error.

SYNTAX:
The syntax for the rewind function in the C Language is:
rewind(FILE pointer);
example : rewind(fp);
RETURNS:
The rewind function does not return anything.
24

Program :

#include <stdio.h>
void main()
{
char str[] = "This is cse department";
FILE *fp;
int ch; /* First let's write some content in the file */
fp = fopen( "file.txt" , "w" );
fwrite(str , sizeof(str),1 , fp );
fclose(fp);
fp = fopen( "file.txt" , "r" );
while(1)
{
ch = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", ch);
}
rewind(fp);
printf("\n");
while(1)
{
ch = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", ch);
}
fclose(fp);
}
25

Let us assume we have a text file file.txt that have the following content
This is cse department
Now let us compile and run the above program to produce the following result
Output :
This is cse department
This is cse department

feof() :
In the C Programming Language, the feof() function tests to see if the end-of-file
indicator has been set for for the file.
Syntax : feof(FILE pointer);
Example : feof(fp);
Returns :
The feof function returns a nonzero value if the end-of-file indicator is set.
Otherwise, it returns zero.
Program :

#include <stdio.h>
#include<stdlib.h>
void main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
if(fp == NULL)
{
printf("can’t open file");
exit(0);
}

while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
26

break ;
}
printf("%c", c);
}
fclose(fp);
}

Until the file pointer reaches the end of the file the contents from the file will be
read and displayed in the console screen.

ferror();
In the C Programming Language, the ferror() function tests to see if there is any
error in the file input and output functions.
Syntax: ferror(FILE pointer);
Example : ferror(fp);
Returns:
The ferror() function returns a nonzero value if the error indicator is set. Otherwise,
it returns zero.
Program :

#include <stdio.h>
void main()
{
FILE *fp;
char c;
fp = fopen("file.txt", "w");
c = fgetc(fp);
if( ferror(fp) )
{
printf("Error in reading from file : file.txt\n");
}
fclose(fp);
}
27

Assuming we have a text file file.txt, which is an empty file. Let us compile and run the
above program that will produce the following result because we try to read a file which
we opened in write only mode.
Output :
Error reading from file "file.txt"

RANDOM ACCESS FILE:


It is used to access file contents randomly by using random access functions such as
fseek(), ftell(), rewind(). It can be applied for both text files and binary files. Compared to
sequential access file, it reduces searching time or execution time.

Example Program:

Manipulations with Student Information:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student
{
int rno;
char name;
}s;
void main()
{
FILE *fp1,*fp2;
int ch,n,f=0,i;
char a;
fp1=fopen(“stu.dat”,”w+b”);
while(1)
{
printf(“1.Add New Record\n2.Display\n3.Modify\n4.Delete\n5.Exit\n”);
printf(“Enter your Choice”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:printf(“Enter your roll number and name :“);
scanf(“%d%s”,&s.rno,&s.name);
fseek(fp1,0,SEEK_END);
fwrite(&s,sizeof(s),1,fp1);
break;
28

case 2:rewind(fp1);
if(fread(&s,sizeof(s),1,fp1))==0)
{
printf(“File is Empty”);
exit(0);
}
rewind(fp1);
printf(“The Records are “);
while((fread(&s,sizeof(s),1,fp1))==1)
{
printf(“%d%s”,s.rno,s.name);
}
break;
case 3:rewind(fp1);
if(fread(&s,sizeof(s),1,fp1))==0)
{
printf(“File is Empty”);
exit(0);
}
rewind(fp1);
printf(“Enter the Roll No”);
scanf(“%d”,&n);
while((fread(&s,sizeof(s),1,fp1))==1)
{
if(s.rno==n)
{
fseek(fp1,-sizeof(s),SEEK_CUR);
printf(“Enter the new roll number and name”);
scanf(“%d%s”,&s.rno,&s.name);
fwrite(&s,sizeof(s),1,fp1);
f=1;
break;
case 4:rewind(fp1);
if(fread(&s,sizeof(s),1,fp1))==0)
{
printf(“File is Empty”);
exit(0);
}
rewind(fp1);
fp2=fopen(“temp.dat”,”w+b”);
printf(“Enter roll number to delete”);
scanf(“%d”,&n);
29

while((fread(&s,sizeof(s),1,fp1))==1)
{
if(s.rno!=n)
{
fwrite(&s,sizeof(s),1,fp2);
}
if(s.rno==n)
{
f=1;
}
}
if(f)
{
printf(“Delete Successful”);
fclose(fp1);
fclose(fp2);
remove(“stu.dat”);
rename(“temp.dat”,”stu.dat”);
fp1=fopen(“stu.dat”,”r+b”);
break;
case 5:printf(“Exit”);
exit(0);
}
}
printf(“Over”);
fclose(fp1);
}

EXAMPLE PROGRAM: TRANSACTION PROCESSING USING RANDOM


ACCESS FILES
The program maintains a bank’s account information—updating existing accounts,
adding new accounts, deleting accounts and storing a listing of all the current accounts in
a text file for printing.

#include <stdio.h>
struct clientData
{
unsigned int acctNum;
char lastName[15];
char firstName[10];
double balance;
30

};

unsigned int enterChoice(void);


void textFile(FILE *readPtr);
void updateRecord(FILE *fPtr);
void newRecord(FILE *fPtr);
void deleteRecord(FILE *fPtr);

int main(void)
{
FILE *cfPtr;
unsigned int choice;
if ((cfPtr = fopen("credit.dat", "rb+")) == NULL)
{
puts("File could not be opened.");
}
else
{
while ((choice = enterChoice()) != 5)
{
switch (choice)
{
case 1:
textFile(cfPtr);
break;

case 2:
updateRecord(cfPtr);
break;

case 3:
newRecord(cfPtr);
break;

case 4:
deleteRecord(cfPtr);
break;

default:
puts("Incorrect choice");
break;
}
31

}
fclose(cfPtr);
}
}

void textFile(FILE *readPtr)


{
FILE *writePtr;
int result;
struct clientData client = {0, "", "", 0.0};
if ((writePtr = fopen("accounts.txt", "w")) == NULL)
{
puts("File could not be opened.");
}
else
{
rewind(readPtr);
fprintf(writePtr, "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First
Name","Balance");
while (!feof(readPtr))
{
result = fread(&client, sizeof(struct clientData), 1, readPtr);
if (result != 0 && client.acctNum != 0)
{
fprintf(writePtr,"%-6d%-16s%-11s%10.2f\n",
client.acctNum, client.lastName, client.firstName, client.balance);
}
}
fclose(writePtr);
}
}

void updateRecord(FILE *fPtr)


{
unsigned int account;
double transaction;
struct clientData client = {0, "", "", 0.0};
printf("%s", "Enter account to update ( 1 - 100 ): ");
scanf("%d", &account);
fseek(fPtr, (account - 1) * sizeof(struct clientData), SEEK_SET);
fread(&client, sizeof(struct clientData), 1, fPtr);
32

if (client.acctNum == 0)
{
printf("Account #%d has no information.\n", account);
}
else
{
printf("%-6d%-16s%-11s%10.2f\n\n", client.acctNum, client.lastName,
client.firstName, client.balance);
printf("%s", "Enter charge ( + ) or payment ( - ): ");
scanf("%lf", &transaction);
client.balance += transaction; // update record balance
printf("%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName,
client.firstName, client.balance);
fseek(fPtr, (account - 1) * sizeof(struct clientData), SEEK_SET);
fwrite(&client, sizeof(struct clientData), 1, fPtr);
}
}

void deleteRecord(FILE *fPtr)


{
struct clientData client;
struct clientData blankClient = {0, "", "", 0};
unsigned int accountNum;
printf("%s", "Enter account number to delete ( 1 - 100 ): ");
scanf("%d", &accountNum);
fseek(fPtr, (accountNum - 1) * sizeof(struct clientData), SEEK_SET);
fread(&client, sizeof(struct clientData), 1, fPtr);
if (client.acctNum == 0)
{
printf("Account %d does not exist.\n", accountNum);
}
else
{
fseek(fPtr, (accountNum - 1) * sizeof(struct clientData), SEEK_SET);
fwrite(&blankClient, sizeof(struct clientData), 1, fPtr);
}
}

void newRecord(FILE *fPtr)


{
struct clientData client = {0, "", "", 0.0};
unsigned int accountNum;
33

printf("%s", "Enter new account number ( 1 - 100 ): ");


scanf("%d", &accountNum);

fseek(fPtr, (accountNum - 1) * sizeof(struct clientData), SEEK_SET);


fread(&client, sizeof(struct clientData), 1, fPtr);
if (client.acctNum != 0)
{
printf("Account #%d already contains information.\n", client.acctNum);
}
else
{
printf("%s", "Enter lastname, firstname, balance\n? ");
scanf("%14s%9s%lf", &client.lastName, &client.firstName,
&client.balance);
client.acctNum = accountNum;
fseek(fPtr, (client.acctNum - 1) * sizeof(struct clientData), SEEK_SET);
fwrite(&client, sizeof(struct clientData), 1, fPtr);
}
}

unsigned int enterChoice(void)


{
unsigned int menuChoice;
printf("%s","\nEnter your choice\n 1 - store a formatted text file of accounts called
accounts.txt for printing\n 2 - update an account\n 3 - add a new account\n 4 - delete an
account\n 5 - end program\n");
scanf("%u", &menuChoice);
return menuChoice;
}

COMMAND LINE ARGUMENT

If any input value is passed through command prompt at the time of running of
program is known as command line argument. It is a concept to passing the arguments to
the main() function by using command prompt.

When Use Command Line Argument


34

To use command line arguments in your program, you must first understand the full
declaration of the main function, which previously has accepted no arguments. In fact,
main can actually accept two arguments: one argument is number of command line
arguments, and the other argument is a full list of all of the command line arguments.

In Command line arguments application main() function will takes two arguments
that is;

The full declaration of main looks like this:


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

 argc – argument count


 argv – argument vector
argc - argc is an integer type variable and it holds total number of arguments which is
passed into main function. It takes number of arguments in the command line including
program name.
argv[] - argv[] is a char* type variable, which holds actual arguments which is passed
to main function.

Example of Command line argument


#include<stdio.h>
void main(int argc, char* argv[])
{
int sum;
sum=atoi(argv[1])+atoi(argv[2]);
printf(“sum=%”,sum);
}
Output
Compilation : gcc add.c
Execution : ./a.out 10 20
sum=30
35

Example of Command line argument


#include<stdio.h>
void main(int argc, char* argv[])
{
int i;
printf("Total number of arguments: %d",argc);
for(i=0;i< argc;i++)
{
printf("\n %d argument: %s",i,argv[i]);
}
}
Output
Compilation : gcc mycmd.c
Execution : ./a.out 10 20
Number of Arguments: 3
0 argument: a.out
1 argument: 10
2 argument: 20

Example of Command line argument


#include<stdio.h>
void main(int argc, char* argv[])
{
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
36

}
Output
Compilation : gcc mycmd.c
Execution : ./a.out this is a program
Program name : a.out
1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)
Explanation: In the above example.
Example
argc = 5
argv[0] = "mycmd"
argv[1] = "this"
argv[2] = "is"
argv[3] = "a"
argv[4] = "program"
argv[5] = NULL

Write a C Program to find the factorial of any number using command line argument.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int num, fact;
if(argc != 2)
{
printf("Invalid Usage.\n\n");
printf("Usage: ./a.out <number>\n");
return 0;
37

}
num = atoi(argv[1]);

if(num<0)
{
printf("Error: Factorial of negative number doesn't exist.");
return 1;
}
fact = 1;
while(num>1)
{
fact = fact * num;
num--;
}
printf("%d\n", fact);
}

EXAMPLE PROGRAMS

//FILE COPY

# include <stdio.h>
void main()
{
char c,fname[20];
FILE *fptr1,*fptr2 ;
fptr1 = fopen(“abc.txt”, "r") ;
if(fptr==NULL)
printf("\nSorry.. File Not Found");
else
{
fptr2 = fopen("dest.tx","w") ;
38

printf("\nThe Content of Source File \n\n");


while(c = fgetc(fptr1)!=EOF)
{
Printf(“%d,c) ;
fputc(c,fptr2);
}
fclose(fptr1) ;
fclose(fptr2);
printf("\n\nThe Content of Destination File \n\n");
fptr2 = fopen("dest.tx","r") ;
while(c = fgetc(fptr2) !=EOF)
Printf(“%d”,c) ;
fclose(fptr2);
}
}

MERGING TWO FILES


PROGRAM:
# include <stdio.h>
void main()
{
char c ;
FILE *fptr1, *fptr2, *fptr3 ;
printf("Enter the text to be stored in the file - 1.\n") ;
printf("Use ^Z or F6 at the end of the text and press ENTER : \n\n") ;
fptr1 = fopen("FIRST.TXT","w") ;
while((c = getc(stdin)) != EOF)
fputc(c, fptr1) ;
fclose(fptr1) ;
39

printf("\nEnter the text to be stored in the file - 2.\n") ;


printf("Use ^Z or F6 at the end of the text and press ENTER : \n\n") ;
fptr2 = fopen("SECOND.TXT","w") ;
while((c = getc(stdin)) != EOF)
fputc(c, fptr2) ;
fclose(fptr2) ;
fptr1 = fopen("FIRST.TXT","r") ;
fptr2 = fopen("SECOND.TXT","r") ;
fptr3 = fopen("MERGE.TXT","w") ;
while((c = fgetc(fptr1)) != EOF)
fputc(c, fptr3) ;
fclose(fptr1) ;
while((c = fgetc(fptr2)) != EOF)
fputc(c, fptr3) ;
fclose(fptr2) ;
fclose(fptr3) ;
printf("\nThe content of the merged file is : \n\n") ;
fptr3 = fopen("MERGE.TXT", "r") ;
while((c = fgetc(fptr1)) != EOF)
putchar(c) ;
fclose(fptr3) ;
}

//STUDENT DETAILS
# include <stdio.h>
void main()
{
FILE *fptr ;
int i, n, rollno, s1, s2 ;
40

char name[10] ;
fptr = fopen("STUDENT.DAT", "w") ;
printf("Enter the number of students : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the roll number : ") ;
scanf("%d", &rollno) ;
printf("\nEnter the name : ") ;
scanf("%s", name) ;
printf("\nEnter the marks in 2 subjects : ") ;
scanf("%d %d", &s1, &s2) ;
fprintf(fptr, "%d %s %d %d \n", rollno, name, s1, s2) ;
}
fclose(fptr) ;
fptr = fopen("STUDENT.DAT", "r") ;
printf("\nRoll No. Name \t\t Sub1 \t Sub2 \t Total\n\n") ;
for(i = 0 ; i < n ; i++)
{
fscanf(fptr,"%d %s %d %d \n", &rollno, name, &s1, &s2) ;
printf("%d \t %s \t\t %d \t %d \t %d \n", rollno, name,s1, s2, s1 + s2) ;
}
fclose(fptr) ;
}
//No. of characters in a file
#include<stdio.h>
#include<conio.h>
Void main()
41

{
char ch;
int count=0;
FILE *fptr;
fptr=fopen("text.txt","w");
if(fptr==NULL)
{
printf("File can't be created\a");
exit(0);
}
printf("Enter some text and press enter key:\n");
while((ch=fgetc(fptr))!=EOF')
{
fputc(ch,fptr);
}
fclose(fptr);
fptr=fopen("text.txt","r");
printf("\nContents of the File is:");
while((ch=fgetc(fptr))!=EOF)
{
count++;
printf("%c",ch);
}
fclose(fptr);
printf("\nThe number of characters present in file is: %d",count);
getch();
}
//NO OF LINES IN A FILE
#include<stdio.h>
#include<stdlib.h>
void main()
42

{
FILE *fp;
char ch;
int line=0;
fp=fopen("in.txt","w");
if(fp==NULL)
{
printf("cant open");
exit(1);
}
printf("enter a character\n");
while((ch=getchar())!='$')
{
fputc(ch,fp);
}
fclose(fp);
fp=fopen("in.txt","r");
if(fp==NULL)
{
printf("cant open");
exit(1);
}
printf("content present in a file\n");
while((ch=fgetc(fp))!=EOF)
{
putchar(ch);
if(ch=='\n')
{
line++;
}
}
fclose(fp);
printf("no of lines=%d\n",line);
}
43

Important Questions

1. Why files are needed?


2. Enlist the File Operations
3. How to open a file?
4. List the opening modes in standard I/O
5. How to close a file?
6. What are two main ways a file can be organized?
7. Write the functions for random access file processing.
8. Give an example for fseek().
9. Give an example for ftell(), rewind().
10. Write short notes on fwrite()

Part B Question

1. Explain about files and with it types of file processing.


2. Compare sequential access and random access.
3. Write a C program to read name and marks of n number of students from user and store
them in a file.
4. Write a C program to write all the members of an array of strcures to a file using fwrite().
Read the array from the file and display on the screen.
5. Explain in detail about random access file.

You might also like