You are on page 1of 92

Presented by: P11

Dr. Rakesh Rathi


Assistant Professor & Head
Department of Computer Science and IT
Govt. Engineering College, Ajmer
 We use different files in our daily life.

For Example:
 We may keep all of our certificates in a file and stick label on it with the heading ‘My Certificate file’.
 Bank people store all their ‘customer’ transactions in a file.

 File is used to store ‘data’.

 A file can be defined as an organized collection of data.

 We arrange the available data in a specific format and then store it in the form of a file.

empno ename salary


1001 Srinu 5000.00 1001 Srinu 5000.00
1002 Vani 8900.75 1002 Vani 8900.75
1003 Ganesh 9000.50 1003 Ganesh 9000.50

Employees’ data on paper File on hard disk

Storage of data on hard disk is called a file

File Concept by Dr. Rakesh Rathi 2


 There are 4 important advantages of storing data in a file:
 When the data is stored in a file, it is stored permanently. This means that even though the computer is
switched off, the data is not removed from the memory since the file is stored on the hard disk or CD. This file data
can be utilized later, whenever required.
 It is possible to update the file data. For example, we can add new data to the existing file, delete unnecessary
data from the file and modify the available data on the file. This makes the file more useful.
 Once the data is stored in a file, the same data can be shared by various programs. For example, once
employee data is stored in a file with the name ‘empdata’, the same file can be used in a program to calculate
employees’ net salaries or in another program to calculate income tax payable by the employees.
 Files are highly useful to store huge amount of data. For example, voters’ list or census data.

 To create a file, we should first open a file to accept data. Then store the data into the file and finally
close the file.

File Concept by Dr. Rakesh Rathi 3


 We should use fopen() function to open file.

 This function accepts ‘filename’ and ‘open mode’ in which to open the file.

fopen(“file name”, “open mode”);


 Here, the ‘file name’ represents a name on which the data is stored.

 A file name should follow some rules:

1. The file name should not be more than 8 characters. We can add another 3 characters as extension.
The extension specifies the nature of the file.
Myfile /* filename without any extension */
myfile.txt /* a text file */
manager.bin /* a binary file */
employee.dat /* a data file */
2. We can use alphabets (A to Z and a to z) and numeric digits (0 to 9) and underscore ( _ ) in the file
names. We should not use special characters like *, #, ?, <, +, “ etc in a file name. Also, we should
never use blank space in a file name.

File Concept by Dr. Rakesh Rathi 4


myfile9.txt /* valid */
emp_sal /* valid */
stud*1 /* invalid */
my phone /* invalid */
 The file ‘open mode’ represents the purpose of opening the file.

File open mode Meaning


To write data into file. If any data is already present in the file, it would be deleted and
w
the present data will be stored.
r To read data from the file.
a To append data to the file. Appending means adding at the end of existing data.
w+ To write and read data of a file. The previous data in the file will be deleted.
r+ To read and write data into a file. The previous data in the file will not be deleted.
a+ To append and read data of a file. Data can be added and read from the file.

File Concept by Dr. Rakesh Rathi 5


 When fopen() function is used to open a file, it returns a pointer to the beginning of the file. This is called
‘file pointer’.
FILE *fp;
 Now, we can open a file, using fopen() function.

fp = fopen(“myfile.txt”, “w”);

What happens when the file is not opened due to some internal problem?
In that case, the file pointer shows NULL. So, we can detect whether the file is properly opened or not by
checking the file pointer is NULL or not.

if(fp == NULL)
{
printf(“\nFile not OPENED”);
return;
}

File Concept by Dr. Rakesh Rathi 6


 A file which is opened should be closed using fclose() function.

 Once a file is opened but not closed, then the data of the file may be corrupted or deleted.

 It is mandatory to close the file.

fclose(fp);
 Here, the file pointed by the pointer ‘fp’ is closed.

 It means fp is deleted from the memory.

 Once the pointer to the file is lost, the file data will become inaccessible.

 If we want to do any work with the file again, we should once again open the file using fopen() function.

File Concept by Dr. Rakesh Rathi 7


Sequential files:
In this type of files, data are kept sequentially.

If we want to read the last record of the file then it is expected to read all the records before it.

It takes more time for accessing the records.

For example:
 If we want to access the 10th record then the first nine records should be read sequentially for reaching the 10 th
record.

Random access files:


In this type of files, data can be read and modified randomly.

It takes less access time as compared to the sequential files.

For example:
 If we want to read the last record of a file, we can directly read the same record.

File Concept by Dr. Rakesh Rathi 8


 There are two types of files that can be created in C.

Types of files

Text files Binary files

Unformatted Text files

formatted Text files

Types of files in C Language

File Concept by Dr. Rakesh Rathi 9


 We can store individual characters in a text file and read them whenever required.

 This is possible using the following functions:

 putc( ): This function is useful to write a single character into a file. For example, to store a character
into a file shown by the file pointer ‘fp’, we can write.
putc(char, fp);
 getc(): This function is useful to read a single character from a file. For example, to read a character
from the file represented by the file pointer ‘fp’, we can write.

char ch = getc(fp);
 When storing a data into a text file, we should press Cntrl+z to represent the end of the file.

 In case of UNIX, press Cntrl+d.

 When these key are pressed, the C compiler recognizes it as end of the file.

 When reading data, to identify the end of file, we can use a macro EOF which represents the end of file
whose value becomes -1 at the end.
 So, when EOF becomes -1, we need not continue reading because we reached the end of file.

 The function putc() and getc() are defined in the header file <stdio.h>.

File Concept by Dr. Rakesh Rathi 10


Program 1: while((ch = getchar()) != EOF)
Program to store a group of characters into a text file. putc(ch, fp);
#include<stdio.h> /* close the file */
#include<conio.h> fclose(fp);
void main() getch();
{ }
char ch;
/* declare file pointer */
FILE *fp;
/* open the file for writing data */
fp = fopen(“myfile.txt”, “w”);
/* store the data into file */
OUTPUT
printf(“\nEnter text:\n”);

File Concept by Dr. Rakesh Rathi 11


Program 1:
Program to store a group of characters into a text file.
Some important Points:
We are opening the file in “w” mode. Since the file is not present already, we are opening the file as a
fresh file.
If the file is already present and if we open it in “w” mode, then the available data in the file will be
deleted and the file will be created as a new file.
We can view the data stored in the file, by using DOS command.

C:\>type myfile.txt
This command displays the content of myfile.txt file.

We should use cat command in Unix to view the content of a file.

If we run program second time.

We can see that the earlier data in the file is lost and we need to enter new data.

In this way, every time the program is run, the previous data is lost.

File Concept by Dr. Rakesh Rathi 12


Program 1:
Program to store a group of characters into a text file.
Some important Points:
If we want to keep the previous data and add the newly typed data at the end of existing data of the file,
then we should open the file in “a” mode.
fp = fopen(“myfile.txt”, “a”);

Program to do yourself:
Write a C program to append the already stored data of the file and enter the new data to the file.

File Concept by Dr. Rakesh Rathi 13


Program 2: while((ch = getc(fp)) != EOF)
Program to read characters from a text file. putchar(ch);
#include<stdio.h> /* close the file */
#include<conio.h> fclose(fp);
void main() getch();
{ }
char ch;
/* declare file pointer */
FILE *fp;
/* open the file for reading data */
fp = fopen(“myfile.txt”, “r”);
/* read character by character and display */
OUTPUT
printf(“\nThe file contents:\n”);

File Concept by Dr. Rakesh Rathi 14


 By default myfile.txt should be available in the current directory (Bin) with C program file and all other
files.
 If the file is available in another directory, then it can be opened by mentioning the file path.

FILE *fp = fopen(“d:\\sub\\myfile.txt”, “r”); /* file is stored at d:\sub */


 When a file is opened in “r” mode, it is not possible to write data into that file.

 Only reading is possible.

 Instead of giving file name directly in the program, it is possible to enter the file name from the keyboard
also.
 This is done by accepting the file name using gets() function.

char fname[15];
printf(“\nEnter filename:”);
gets(fname);
fp = fopen(fname, “r”);
Program to do yourself:
 Write a C program to read the data available in the file, by entering file name form the user.

File Concept by Dr. Rakesh Rathi 15


 It is possible to store a complete string into a file.

 To store a string into a file, we can use fputs() function.

fputs(str, fp);
 To read a string from a file, we can use fgets() function.

fgets(string name, length, fp);


 Here, ‘length’ represents the length of the string to be read from the file.

 When we reach the end of the file, we will get a NULL string.

 So, we should continue reading as long as NULL is not read.

while((fgets(str, 80, fp)) != NULL)


 Both fputs() and fgets() functions are defined in <stdio.h> header file.

File Concept by Dr. Rakesh Rathi 16


Program 3: gets(fname);
Program to store data in the form of strings into a text /* open the file for writing */
file.
fp = fopen(fname, “w”);
#include<stdio.h>
/* store strings into file */
#include<conio.h>
printf(“\nEnter strings:”);
#include<string.h>
printf(“\nPress <ENTER> to quit.\n”);
void main()
do
{
{
char str[80];
gets(str); /* read string into str */
char fname[15]; /* to store filename */
strcat(str, “\n”); /* add new line character */
FILE *fp;
fputs(str, fp); /* write string into file */
/* enter the file name */
} while(*str != ‘\n’);
printf(“\nEnter filename:”);
/* close the file */

File Concept by Dr. Rakesh Rathi 17


fclose(fp);
getch();
}

OUTPUT

File Concept by Dr. Rakesh Rathi 18


Program 4: gets(fname);
Program to read strings from a text file and display /* open the file for reading */
them.
fp = fopen(fname, “r”);
#include<stdio.h>
/* check if the file exits or not */
#include<conio.h>
if(fp == NULL)
#include<string.h>
{
void main()
printf(“\nFile not Found”);
{
return;
char str[80];
}
char fname[15]; /* to store filename */
/* read strings from file as long as NULL not reached
FILE *fp; */
/* enter the file name */ printf(“\nThe file contents:\n”);
printf(“\nEnter Filename:”); while((fgets(str, 80, fp)) != NULL)

File Concept by Dr. Rakesh Rathi 19


puts(str);
/* close the file */
fclose(fp);
getch();
}

OUTPUT

File Concept by Dr. Rakesh Rathi 20


 So far, we created files and stored raw characters into the files.

 These files are useful just to store characters and retrieve them.

 We cannot do any other operations on the data of these files.

 Hence, they are called unformatted text files.

 If, we want to store different type of data like an integer, a string and a floating point number in a file,
then we need ‘formatted text files’.
 We can create formatted text files using fprintf() and fscanf() functions available in <stdio.h> header file.

 Both fprintf() and fscanf() functions behave exactly like printf() and scanf() functions, except that they
have a file pointer as the first argument.
 fprintf() function is useful to write different types of data at a time into a file.

fprintf(fp, “format string”, variables list); /* syntax */


fprintf(fp, “%d%s%f”, id, name, sal); /* store data in all variables in single statement */
fprintf(fp, “%d\n”, id); /* store variable id data in the file */
fprintf(fp, “%s\n”, name); /* store variable name data in the file */
fprintf(fp, “%f\n”, sal); /* store variable sal data in the file */

File Concept by Dr. Rakesh Rathi 21


 The ‘\n’ character with the format string, attached to the value and stored into the file will help later to
retrieve data properly till the end of the line.
 Function fscanf() is used to retrieve the data from the file.

fscanf(fp, “%d%s%f”, &id, name, &sal);


 Function rewind() should used to bring the file pointer to the beginning of the file.

rewind(fp);

File Concept by Dr. Rakesh Rathi 22


Program 5: printf(“\nEnter Employee ID:”);
Program to store employee id number, name and salary scanf(“%d”, &id);
into a file using fprintf() function.
fflush(stdin);
#include<stdio.h>
printf(“\nEnter Name:”);
#include<conio.h>
scanf(“%s”, name);
void main()
fflush(stdin);
{
printf(“\nEnter Salary:”);
int id;
scanf(“%f”, &sal);
char name[15];
/* store the data into the file */
float sal;
fprintf(fp, “%d\n”, id);
FILE *fp;
fprintf(fp, “%s\n”, name);
/* open the file for writing */
fprintf(fp, “%f\n”, sal);
fp = fopen(“emp.dat”, “w”);
printf(“\nemp.dat file created…”);
/* read data from keyboard */

File Concept by Dr. Rakesh Rathi 23


/* close the file */
fclose(fp);
getch();
}

OUTPUT

File Concept by Dr. Rakesh Rathi 24


Program 6: fscanf(fp, “%d”, &id);
Program to read employee id number, name and salary fscanf(fp, “%s”, name);
from the file using fscanf() function.
fscanf(fp, “%f”, &sal);
#include<stdio.h>
/* display the data */
#include<conio.h>
printf(“\nEmployee ID:%d”, id);
void main()
printf(“\nName:%s”, name);
{
printf(“\nSalary:%.2f”, sal);
int id;
/* close the file */
char name[15];
fclose(fp);
float sal;
getch();
FILE *fp;
}
/* open the file for reading */
fp = fopen(“emp.dat”, “r”);
/* read data from file into variables */ OUTPUT

File Concept by Dr. Rakesh Rathi 25


Program 7: while(response == ‘y’)
Program to write several employees data into a text file {
and read them from the file.
/* read data from keyboard */
#include<stdio.h>
printf(“\nEnter Employee ID:”);
#include<conio.h>
scanf(“%d”, &id);
void main()
fflush(stdin);
{
printf(“\nEnter Name:”);
int id;
scanf(“%s”, name);
char name[15];
fflush(stdin);
float sal;
printf(“\nEnter Salary:”);
FILE *fp;
scanf(“%f”, &sal);
clrscr();
fflush(stdin);
/* open the file for writing */
/* ask to enter next record */
fp = fopen(“manyemp.dat”, “w+”);

File Concept by Dr. Rakesh Rathi 26


printf(“\nEnter New Record (y/n):”); /* read as long as fscanf() does not return EOF */
scanf(“%c”,&response); while(fp !=EOF)
fflush(stdin); {
/* store the data into the file */ /* read data from the file */
fprintf(fp, “%d\n”, id); fscanf(fp, “%d\n”, &id);
fprintf(fp, “%s\n”, name); fscanf(fp, “%s\n”, name);
fprintf(fp, “%f\n”, sal); fscanf(fp, “%f\n”, &sal);
} /* display the data from the file */
/* bring file pointer back to beginning of file */ printf(“\n%10d%20s%12.2f”, id, name, sal);
rewind(fp); }
/* put heading */ /* close the file */
printf(“\n%10s%20s%12s”, “ID”, “EMPLOYEE NAME”, fclose(fp);
“SALARY”);

File Concept by Dr. Rakesh Rathi 27


getch();
}

OUTPUT

File Concept by Dr. Rakesh Rathi 28


 Binary files are useful to store different types of data.

 For example:
 We have details of a bank customer like account number, name of the customer and balance amount in the
account.
 These different types of data can be stored into a structure and then written into a binary file.

 Firstly, we construct the bank customer structure.


struct customer
{
int accno;
char name[20];
float balance;
};
struct customer cust; /* cust is the structure variable */
 The next step is to store this structure data in binary file, as a record.

 This means one structure data is written as one record into the binary file.

File Concept by Dr. Rakesh Rathi 29


 For this purpose, we can use fwrite() function.

fwrite(address of structure variable, size, number of records to write, file pointer);


fwrite(&cust, sizeof(cust), 1, fp);
 Here, &cust is the address of the structure variable.

 The second argument is size of structure variable that represents the number of bytes to be written into
the file.
 Usually, writing one record at a time is done. So, third argument is taken as 1.

 The last argument is file pointer that refers to the file.

Keyboard structure Binary file

Storing data into a binary file

File Concept by Dr. Rakesh Rathi 30


 To read data from the binary file, we can take help of fread() function.

 It reads the records from the binary file, generally one record at a time.

 Its format is same as that of fwrite() function.


fread(&cust, sizeof(cust), 1, fp);
 This will read one record from the file and stores it into the customer structure.

 From the structure, the data can be sent to monitor for display.

 It is also possible to redirect this data to a printer where a printout can be taken.

 we can also store this data in another file for the purpose of using it later.

Binary file structure Monitor

Reading records from a binary file

File Concept by Dr. Rakesh Rathi 31


 While reading records from a binary file, we may reach end of the file which is determined by feof()
function.
 feof() function returns a non-zero value which is treated as true, if the end of the file is reached.

 We can use this function in a loop to perform the tasks as long as end of the file is not reached.
while(!feof(fp))
 This loop is broken when end of binary file is reached.

 Binary files can be opened just like text files in read, write and append modes.

 But we should affix ‘b’ at the end of the file mode.

wb to write data into binary file.


rb to read data from a binary file.
ab to append data to binary file.

Similarly, we can also use w+b, r+b and a+b modes

File Concept by Dr. Rakesh Rathi 32


Program 8: /* cust is the structure variable */
Program to store bank customer data into a structure struct customer cust;
and from there into a binary file.
/* open the bank.dat file for writing */
#include<stdio.h>
FILE *fp;
#include<conio.h>
fp = fopen(“bank.dat, “wb”);
struct customer
/* infinite loop to execute repeatedly */
{
for(;;)
int accno;
{
char name[20];
/* read data from keyboard and store into customer
float balance; structure */
}; printf(“\nEnter account no(0 to stop):”);
void main() scanf(“%d”, &cust.accno);
{ /* when 0 is entered, break the loop */

File Concept by Dr. Rakesh Rathi 33


if(cust.accno == 0)
break;
fflush(stdin);
printf(“\nEnter customer name:”);
gets(cust.name);
printf(“\nEnter balance amount:”);
scanf(“%f”, &cust.balance);
/* write the customer structure data into bank.dat file */
fwrite(&cust, sizeof(cust), 1, fp);
}
printf(“\nbank.dat file is created…”);
fclose(fp);
getch(); } OUTPUT

File Concept by Dr. Rakesh Rathi 34


Program 9: void main()
Program to read bank customer data from a binary file {
and display it on the screen.
struct customer cust;
#include<stdio.h>
int j, k, i=1;
#include<conio.h>
FILE *fp;
#define SPACE(k) for(j=1;j<=k;j++) fprintf(stdout, “ “);
/* open the bank.dat file for reading */
#define LINE for(j=1;j<=80;j++) fprintf(stdout, “-”);
fp = fopen(“bank.dat”, “rb”);
struct customer
/* if the file does not exist, return */
{
if(fp == NULL)
int accno;
{
char name[20];
printf(“\nFile not found”);
float balance;
return;
};
}

File Concept by Dr. Rakesh Rathi 35


/* display heading */ while(!feof(fp))
clrscr(); {
SPACE(26); fprintf(stdout, “\n%10d”, i);
fprintf(stdout, “STATE BANK OF INDIA REPORT\n”); fprintf(stdout, “%10d”, cust.accno);
LINE; fprintf(stdout, “%25s”, cust.name);
fprintf(stdout, “\n%10s”, “SNO”); fprintf(stdout, “%15.2f”, cust.balance);
fprintf(stdout, “%10s”, “ACCNO”); i++; /* this is for generating serial number */
fprintf(stdout, “%25s”, “CUSTOMER NAME”); /* read the next record from the file */
fprintf(stdout, “%15s\n”, “BALANCE”); fread(&cust, sizeof(cust), 1, fp);
LINE; }
/* read first record from the file into the structure */ /* put the cursor into next line */
fread(&cust, sizeof(cust), 1, fp); fprintf(stdout, “\n”);
/* display the record data */ LINE;

File Concept by Dr. Rakesh Rathi 36


fclose(fp);
getch();
}

OUTPUT

File Concept by Dr. Rakesh Rathi 37


 Displaying the report on the screen is a good practice.

 But in many cases, it is advisable to take a printout of the report on a paper for further reference.

 This is achieved with fprintf() function.

 This function can be used to send data to the printer.


fprintf(stdprn, “format string”, variables);
 Here ‘stdprn’ represents the ‘standard printer’ that is connected to the computer.

 Write ‘stdprn’ in place of ‘stdout’ in the whole program to take printout of the output.

File Concept by Dr. Rakesh Rathi 38


 Sometimes we do not want to take a printout of the report.

 We want to store the report in another file so that it can be printed or viewed whenever needed.

 This is also possible using fprintf() function.

 First, we should open a text file for storing the report.

FILE *fp1;
fp1 = fopen(“report.txt”, “w”);

 The next step is to mention this file pointer in the place of “stdout” in fprintf() function.
fprintf(fp1, “format string”, “variables”);

File Concept by Dr. Rakesh Rathi 39


Program 10: void main()
Program to read bank customer data from a binary file {
and storing that data into another file.
struct customer cust;
#include<stdio.h>
int j, k, i=1;
#include<conio.h>
FILE *fp, *fp1;
#define SPACE(k) for(j=1;j<=k;j++) fprintf(fp1, “ “);
/* open the bank.dat file for reading */
#define LINE for(j=1;j<=80;j++) fprintf(fp1, “-”);
fp = fopen(“bank.dat”, “rb”);
struct customer
/* if the file does not exist, return */
{
if(fp == NULL)
int accno;
{
char name[20];
printf(“\nFile not found”);
float balance;
return;
};
}

File Concept by Dr. Rakesh Rathi 40


/* open another file to store report */ fread(&cust, sizeof(cust), 1, fp);
fp1 = fopen(“report.txt”, “w”); /* store the record data into report.txt file */
/* display heading */ while(!feof(fp))
clrscr(); {
SPACE(26); fprintf(fp1, “\n%10d”, i);
fprintf(stdout, “STATE BANK OF INDIA REPORT\n”); fprintf(fp1, “%10d”, cust.accno);
LINE; fprintf(fp1, “%25s”, cust.name);
fprintf(stdout, “\n%10s”, “SNO”); fprintf(fp1, “%15.2f”, cust.balance);
fprintf(stdout, “%10s”, “ACCNO”); i++; /* this is for generating serial number */
fprintf(stdout, “%25s”, “CUSTOMER NAME”); /* read the next record from the file */
fprintf(stdout, “%15s\n”, “BALANCE”); fread(&cust, sizeof(cust), 1, fp);
LINE; }
/* read first record from the file into the structure */ /* put the cursor into next line */

File Concept by Dr. Rakesh Rathi 41


fprintf(stdout, “\n”);
LINE;
/* close both the files */
fclose(fp); Note:
When this program is executed, nothing is displayed on
fclose(fp1);
the screen.
getch(); Go to that directory (or folder) where the program is run.
In that directory, we can see a new file created by the
}
name: report.txt.
We can open the file and view the report in any text editor
like Notepad, Wordpad, or MS word.

OUTPUT

File Concept by Dr. Rakesh Rathi 42


 The data is stored in the form of several records in a binary file.

 Suppose we want to access 4th record, then we should read from the first record till the third record.

 When the third record is read from the file, the file pointer reaches the end of the third record and
hence it will be positioned at the starting of 4th record.
 File pointer moves from byte to byte in the binary file when a reading or writing operation is performed.

 It is possible to position the file pointer at any place directly in the file.

 This is called Random accessing and can be done using fseek() function.

fseek(fp, how many bytes to move, from where);


 Here, ‘from where’ to move the file pointer can be shown by the following constants.

SEEK_SET: to move from the starting of the file.


SEEK_CUR: to move from the current position.
SEEK_END: to move from the file end.

File Concept by Dr. Rakesh Rathi 43


For example:
To move the file pointer 50 bytes from the starting of the file, we can use fseek() function, as.

fseek(fp, 50, SEEK_SET);


To move the file pointer by 10 bytes forward from its current position.

fseek(fp, 10, SEEK_CUR);


To move the file pointer back by 10 bytes from its current position.

fseek(fp, -10, SEEK_CUR);


Here, negative number tells the pointer to move backwards.

To move the file pointer 0 bytes from the end of the file and to position the file pointer at the end of the
file.
fseek(fp, 0, SEEK_END);
While fseek() function is useful to position the file pointer at a specified position, ftell() function returns
the position of the file pointer.
long int position = ftell(fp);
Both fseek() and ftell() functions are available in <stdio.h> header file.

File Concept by Dr. Rakesh Rathi 44


Feof():
The macro feof() is used for detecting if the file pointer is at the end of file or not.

It returns non-zero if the file pointer is at the end of file, otherwise it returns zero.

File Concept by Dr. Rakesh Rathi 45


Program 11: while(!feof(fp))
Program to detect the end of file using the function {
feof(). Also display the file pointer position for detecting
end of file. printf("%c", c);

#include<stdio.h> c=getc(fp);

#include<conio.h> }

void main() c=feof(fp);

{ printf("\nFile pointer at the end of file:%d", c);

char c; getch();

FILE *fp; }

fp=fopen("text.txt","r");
c=feof(fp);
clrscr();
printf("File pointer at the beginning of the file:%d\n", c); OUTPUT

File Concept by Dr. Rakesh Rathi 46


 To know the size of a file, simple logic to be develop.

 First, position the file pointer at the end of the file using fseek().

 Next, read the byte number using ftell().

fseek(fp, 0, SEEK_END); /* Position fp at the end of file */


/* know the last byte number, that gives size of the file */
int size = ftell(fp);

 Here, ‘size’ represents the size of the file in bytes. This logic is useful to know the size of any file.

 In case of binary files, we can also find out how many records are there in the file.
number of records = file size / size of one record.
 We can get the record size using sizeof() operator on the structure stored into the file.

File Concept by Dr. Rakesh Rathi 47


Program 12: struct customer cust;
Program to find the size of file and number of records FILE *fp;
present in the file.
int recsize, no_records;
#include<stdio.h>
long int filesize;
#include<conio.h>
/* open the file in read mode */
struct customer
fp=fopen(“bank.dat”, “rb”);
{
/* check if file exists or not */
int accno;
if(fp == NULL)
char name[20];
{
float balance;
printf(“\nFile does not exist…”);
};
return;
void main()
}
{
/* calculate size of one record */

File Concept by Dr. Rakesh Rathi 48


recsize = sizeof(cust);
printf(“\nRecord size:%d bytes.”, recsize);
/* calculate size of the file */
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
printf(“\nFile size:%ld bytes. “, filesize);
/* calculate number of records */
no_records = filesize/recsize;
printf(“\nThere are %d records in the file.”, no_records);
OUTPUT
/* close the file */
fclose(fp);
getch();
}

File Concept by Dr. Rakesh Rathi 49


 It is possible to update (modify) the contents of any record in a binary file.

For example:
 A customer is depositing or withdrawing money from his account. Then the balance in his account
should be updated accordingly in the file.
 For this purpose, we should follow these steps (Here, we modify or update record in bank.dat file):

1. Accept the customer account number whose record is to be modified. For example, the account number
is 1002. Store it into ‘tempno’ variable.
2. Our assumption is that the account numbers are sequentially stored in the ‘bank.dat’ file as 1001, 1002,
1003, etc. If we deduct 1000 from these account numbers, then they will become 1, 2, 3, etc. These can
be taken as record numbers.
recno = tempno -1000 = 1002 – 1000 = 2nd record.
3. Now, we should position the file pointer in the beginning of second record represented by ‘recno’. This
means move the file pointer till the end of first record, i.e. recno-1.
/* find the record size */
recsize = sizeof(cust);
/* move file pointer to the end of recno – 1 */
position = (recno-1)*recsize;
File Concept by Dr. Rakesh Rathi 50
recno = 1 recno = 2 recno = 3

1001 Tarun Goyal 5000.00 1002 Nihaar Chandra 9885.50 1003 Somesh Prajapati 12000.75

This record is to be modified


fp move fp
To read a record, place the file pointer at the end of its previous record

4. Place the file pointer at the position calculated. we can use fseek() function for this.
fseek(fp, position, SEEK_SET);
5. Read the record into a structure using fread() function.
fread(&cust, sizeof(cust), 1, fp);

File Concept by Dr. Rakesh Rathi 51


6. Once modification is done, we should rewrite this record into the file. Since, we read the record, the file
pointer will be positioned at the end of the record. Again we should bring the file pointer to the
beginning of the record using fseek() function and then write the modified record into the file using
fwrite() function.

/* bring fp to the beginning of current record */


fseek(fp, -recsize, SEEK_CUR);
/* write the modified record into file */
fwrite(&cust, sizeof(cust), 1, fp);

Note:
 When a record is read from the file, the file pointer starts reading from the beginning of that record and
reaches the end of that record.
 When a record is written into a file, the file pointer writes that data into the file and reaches the end of
that record form the beginning.
 So, when the reading and writing operation is finished, the file pointer would be placed at the end of
that record.

File Concept by Dr. Rakesh Rathi 52


Program 13: {
Program to read the contents of a record, update its struct customer cust;
contents and then rewrite the updated record into the
file. FILE *fp;

#include<stdio.h> int recsize, tempno, recno, position;

#include<conio.h> char ch;

#include<ctype.h> float amount;

struct customer /* open the file for reading and writing */

{ fp = fopen(“bank.dat”, “r+b”);

int accno; /* check if file exists or not */

char name[20]; if(fp == NULL)

float balance; {

}; printf(“\nFile does not exist…”);

void main() return;

File Concept by Dr. Rakesh Rathi 53


} printf(“\n%d\t%s\t%.2f”, cust.accno, cust.name,
cust.balance);
/* read account number */
/* read the choice */
printf(“\nEnter account no:”);
printf(“\nEnter D-Deposit, W-Withdraw:”);
scanf(“%d”, &tempno);
fflush(stdin);
/* find the record number */
ch = getchar();
recno = tempno – 1000;
if(toupper(ch) == ‘D’)
/* position the file pointer before the record */
{
recsize = sizeof(cust);
printf(“\nEnter deposit amount:”);
position = (recno-1)*recsize;
scanf(“%f”, &amount);
/* put the file pointer at the beginning of record */
cust.balance += amount;
fseek(fp, position, SEEK_SET);
}
/* read that record to be modified */
else if(toupper(ch) == ‘W’)
fread(&cust, sizeof(cust), 1, fp);

File Concept by Dr. Rakesh Rathi 54


{ fwrite(&cust, sizeof(cust), 1, fp);
printf(“\nEnter withdraw amount:”); printf(“\nRecord Modified”);
scanf(“%f”, &amount); /* close the file */
cust.balance -= amount; fclose(fp);
} getch();
else }
{
printf(“\nWRONG INPUT….”);
return;
}
/* put the file pointer back to beginning of record */
fseek(fp, -recsize, SEEK_CUR);
/* rewrite the modified record */ OUTPUT

File Concept by Dr. Rakesh Rathi 55


 We do not have any function available in C language to remove (delete) a specific record from a file.

 So, for this we should create our own logic.

 The simple logic would be to copy all the records of the file into a new file leaving the record which to be
deleted.
 The following are the steps to delete a record from ‘bank.dat’ file:

1. we should store all the records from bank.dat file into a temporary file, except the record which is to be
deleted.
 We should open the bank.dat file in ‘rb’ mode and temp.dat file in ‘wb’ mode.
 Read the records one by one from the bank.dat file.
 If the record is not marked for deletion, then write it into temp.dat file.
 Read the next record and repeat the same procedure.

2. Delete the bank.dat file, using remove() function.


remove(“bank.dat”);
 Rename the temp.dat file as bank.dat file, using rename() function.

rename(“temp.dat”, “bank.dat”);
File Concept by Dr. Rakesh Rathi 56
 Both remove() and rename() functions are defined in <stdio.h> header file.

Note:
 Both remove() and rename() functions work properly after closing the files.

 It means, we can remove a file or rename a file, only after closing it using fclose() function.

File Concept by Dr. Rakesh Rathi 57


Program 14: struct customer cust;
Program to delete a particular record from the bank.dat FILE *fp, *fp1;
file. The account number of the record should be given
by the user. int tempno;

#include<stdio.h> /* open bank.dat file in read mode */

#include<conio.h> fp = fopen(“bank.dat”, “rb”);

struct customer /* open temp.dat file in write mode */

{ fp1 = fopen(“temp.dat”, “wb”);

int accno; /* accept account number of the record to delete */

char name[20]; printf(“Enter account number:”);

float balance; scanf(“%d”, &tempno);

}; /* read records from bank.dat and copy into temp.dat


except the record with tempno */
void main()
fread(&cust, sizeof(cust), 1, fp);
{

File Concept by Dr. Rakesh Rathi 58


while(!feof(fp)) /* delete bank.dat file */
{ remove(“bank.dat”);
if(tempno != cust.accno) /* rename temp.dat file as bank.dat */
{ rename(“temp.dat”, “bank.dat”);
/* write into temp.dat */ printf(“\nOne record deleted…”);
fwrite(&cust, sizeof(cust), 1, fp1); getch();
} }
/* read the next record from bank.dat */
fread(&cust, sizeof(cust), 1, fp);
}
/* close both the files */
fclose(fp);
fclose(fp1); OUTPUT

File Concept by Dr. Rakesh Rathi 59


 The header file <dir.h> contains a structure ‘ffblk’ that stores the file information like file name, file date
and time, file size, etc.
For example:
 ‘ff_name’ is the structure element which contains the name of the file.

 There are two function findfirst() and findnext() in <dir.h> which can be used to retrieve the files from the
directory.
 The findfirst() function is useful to find the first file in the directory.
findfirst(pathname, address of structure-variable, attribute);
 Here, ‘pathname’ can be written as ‘*.*’ which represents all files to be listed.

 ‘attribute’ can be 0 which represents all normal files, except hidden files.
ret_code = findfirst(“*.*”, &file, 0);
 It will list all the files available in the current directory.

 Here, ret_code represents the return code which is 0 if file is found.

File Concept by Dr. Rakesh Rathi 60


 Function findnext() searches for the next file in the directory.

 The findnext() function takes only the address of structure variable.

ret_code = findnext(&file);

File Concept by Dr. Rakesh Rathi 61


Program 15: ret_code = findfirst(“*.*”, &file, 0);
Program to list all the files in the current directory. /* if search is successful then return code is 0 */
#include<stdio.h> while(ret_code == 0)
#include<conio.h> {
#include<dir.h> /* display the file name */
void main() printf(“\n%s”, file.ff_name);
{ /* find the next file in the directory */
/* create ffblk structure variable */ ret_code = findnext(&file);
struct ffblk file; }
/* declare return code */ getch();
int ret_code; }
/* find the first file in the directory while searching for all
files. */

File Concept by Dr. Rakesh Rathi 62


OUTPUT

File Concept by Dr. Rakesh Rathi 63


 While performing read or write operations in the file, few times, we do not get results successfully.

 The reason may be that the mode of reading or writing operation may not be correct.

 The C language provides two functions for searching errors:

 ferror():
 This function find out error occurred while read/write operation of a file.
 It returns ‘0’ while the attempt is successful otherwise non-zero in case of failure.

 perror():
 This function prints the error messages specified by the compiler.

File Concept by Dr. Rakesh Rathi 64


Program 16: if(fp == NULL)
Program to detect an error with read/write operation of a {
file.
puts(“File not Found…”);
#include<stdio.h>
return;
#include<conio.h>
}
#include<process.h>
while(next == ‘Y’)
void main()
{
{
printf(“\nEnter Name:”);
FILE *fp;
gets(name);
char next = ‘Y’;
printf(“\nEnter marks:”);
char name[25];
scanf(“%d”, &marks);
int marks;
p = marks/6;
float p;
fprintf(fp, “%s %d %f”, name, &marks, &p);
fp = fopen(“marks.dat”, “r”);

File Concept by Dr. Rakesh Rathi 65


if(ferror(fp)) }
{
printf(“\nUnable to write data?”);
printf(“\nFile open mode is incorrect.”);
return;
}
printf(“Continue(Y/N):”);
fflush(stdin);
next = getche();
} OUTPUT
/* close the file */
fclose(fp);
getch();

File Concept by Dr. Rakesh Rathi 66


Program 17: {
Program to detect and print the error message using c = fgetc(fp);
perror() function.
if(ferror(fp))
#include<stdio.h>
{
#include<conio.h>
perror(file);
#include<process.h>
getch();
void main()
return;
{
}
FILE *fp;
else
char c’;
printf(“%c”, c);
char file[] = “lines.txt”;
}
fp = fopen(file, “w”);
/* close the file */
while(!feof(fp))
fclose(fp);

File Concept by Dr. Rakesh Rathi 67


getch();
}

OUTPUT

File Concept by Dr. Rakesh Rathi 68


 ftell():
 It is file function.
 It returns the current position of the file pointer.
 It returns the pointer from the beginning of file.
 The current position of the file is detected with this function.

 rewind():
 This function resets the file pointer at the beginning of the file.

File Concept by Dr. Rakesh Rathi 69


Program 18: while(!feof(fp))
Program to print the current position of the file pointer in {
the file using the ftell() function.
printf("%c\t", ch);
#include<stdio.h>
printf("%d\n", ftell(fp));
#include<conio.h>
ch=getc(fp);
void main()
}
{
fclose(fp);
char ch;
getch();
FILE *fp;
}
fp=fopen("text.txt","r");
fseek(fp,21,SEEK_SET);
ch=fgetc(fp);
clrscr();
printf("\n"); OUTPUT

File Concept by Dr. Rakesh Rathi 70


Program 19: printf("Before rewind():");
Program to show how rewind() function works. while(!feof(fp))
#include<stdio.h> {
#include<conio.h> c=fgetc(fp);
void main() printf("%c", c);
{ }
char c; printf("\n\n");
FILE *fp; printf("\bAfter rewind():");
fp=fopen("text.txt","r"); rewind(fp);
clrscr(); while(!feof(fp))
fseek(fp,12,SEEK_SET); {
printf("\nPointer is at position: %d\n", ftell(fp)); c=fgetc(fp);
printf("\n"); printf("%c", c);

File Concept by Dr. Rakesh Rathi 71


}
fclose(fp);
getch();
}

OUTPUT

File Concept by Dr. Rakesh Rathi 72


 Text files can be copied from one file to other or in many files.

 When we attempt to open binary files such as .EXE in text mode, unexpectedly the process of getting
characters would stop.
 Because whenever ASCII value 26 is observed coping work stops due to EOF().

 Another approach to copy such binary files are with low level disk I/O.

 In low level disk I/O operation, data cannot be written as character by character or with sequence of
characters as it carried in the high level disk I/O functions.
 Buffers are used to carry the read and write operations and programmer needs to declare the
appropriate buffer size.
 In the low level operation, a number is assigned to the file and the number is used to refer the file.

File Concept by Dr. Rakesh Rathi 73


Low level disk I/O operations:
Opening the file:
 To open a file or files open() function is used.
 This function is defined in ‘io.h’ header file.

int open(const char *f_name, int access, unsigned mode);


 If open() returns -1, it means that the file could not be opened otherwise the file is successfully opened.

Mode Meaning
O_APPEND Opens a file in append mode.
O_WRONLY Creates a file for writing only.
O_RDONLY Opens a file for writing only.
O_RDWR Opens a file for read/write operations.
O_BINARY Opens a file in binary mode.
O_CREATE Opens a new file for writing.
O_EXCEL When used with O_CREATE, if a file exists it is not overwritten.
O_TEXT Creates a text file.
File Concept by Dr. Rakesh Rathi File opening modes 74
 When O_CREATE flag is used, it also requires permission argument to verify the read/write status of
the file.

Argument Meaning
S_IWRITE Writing to the file allowed.
S_IREAD Reading from the file allowed.
Permission Argument
 The programmer need to include the header file ‘stat.h’ and ‘types.h’ along with ‘fcntl.h’.

 Writing the file:


 The write() function is used to write() data into the file.
 This function is defined in ‘io.h’ header file.

int write(int handle, void *buf, unsigned nbyte);


 Returns the number of bytes written or -1 if an error occurs.

File Concept by Dr. Rakesh Rathi 75


 Reading the file:
 The read() function reads a file.

int read(int handle, void *buf, unsigned len);


 Upon successful end, it returns an integer specifying the number of bytes placed in the buffer; if the file was
opened in text mode, read does not count carriage returns or ctrl-Z characters in the number of bytes read.
 On error, it return -1 and sets errno.

 Closing a file:
 The close() function closes the file.
 This function is defined in ‘io.h’ header file.

int _close(int handle);


int close(int handle);
 Upon successful finish, close & _close return 0; otherwise, they return -1 and set errno.

File Concept by Dr. Rakesh Rathi 76


Program 20: puts("\nEnter a file name:");
Program to enter text through keyboard and store it on gets(file);
the disk. Use low-level disk I/O operations.
s=open(file, O_CREAT | O_TEXT);
#include<stdio.h>
if(s==-1)
#include<conio.h>
puts("\nFile does not exits");
#include<io.h>
else
#include<fcntl.h>
{
void main()
puts("Enter text below:");
{
for(c=0;c<=16;c++)
char file[10];
{
char buff[18];
buff[c]=getche();
int s,c;
}
clrscr();
buff[c]='\0';

File Concept by Dr. Rakesh Rathi 77


write(s,buff,18);
close(s);
}
getch();
}

OUTPUT

File Concept by Dr. Rakesh Rathi 78


Program 21: puts("\nEnter a file name:");
Program to read text from a specified file from the disk. gets(file);
Use low-level disk I/O operations.
s=open(file, O_RDONLY);
#include<stdio.h>
if(s==-1)
#include<conio.h>
{
#include<io.h>
puts("\nFile does not exits.");
#include<fcntl.h>
exit(1);
#include<process.h>
}
void main()
else
{
{
char file[10], ch;
while(!eof(s))
int s;
{
clrscr();
read(s, &ch, 1);

File Concept by Dr. Rakesh Rathi 79


putch(ch);
}
close(s);
}
getch();
}

OUTPUT

File Concept by Dr. Rakesh Rathi 80


 Setting Buffer:
 The size of buffer can be set using the setbuf() buffer.
 This function is defined in ‘stdio.h’ header file.

void setbuf(FILE *fp, char *buffer);

File Concept by Dr. Rakesh Rathi 81


Program 22:
Program to set a buffer size using setbuf() function.
#include<stdio.h>
#include<conio.h>
void main()
{
char buff[22];
clrscr();
setbuf(stdout,buff);
printf("\nThis book teaches C"); OUTPUT
fflush(stdout);
getch();
}

File Concept by Dr. Rakesh Rathi 82


Program 23: /* read char by char from the file till the end of the file
*/
Program to count the number of lines, words and
characters in a text file. while((ch = getc(fp)) != EOF)
#include<stdio.h> {
#include<conio.h> /* count chars without counting spaces */
void main() if(ch != ' ')
{ cc++;

FILE *fp; /* count spaces to know the words */

char ch; if(ch == ' ')

int cc=0, cw=0, lc=0; cw++;

clrscr(); /* count Enter key strokes to know the lines */

/* open a file that contains some text */ if(ch == '\n')

fp=fopen("textfile.txt", "r"); lc++;


}

File Concept by Dr. Rakesh Rathi 83


/* display the results */
printf("\nNo. of characters: %d", cc-lc); /* reduce \n
chars */
printf("\nNo. of words: %d", cw+lc); /* add no. of lines */
printf("\nNo. of lines: %d", lc);
/* close the file */
OUTPUT
fclose(fp);
getch();
}

File Concept by Dr. Rakesh Rathi 84


Function Operation
fopen() Creates a new file for read/write operation
fclose() Closes a file associated with file pointer
closeall() Closes all files opened with fopen()
fgetc() Reads the character from current pointer position and advances the pointer to
the next character
getc() Same as fgetc()
fprintf() Writes all types of data values to the file
fscanf() Reads all types of data values from a file
putc() Writes characters one by one to a file
fputc() Same as putc()
gets() Reads a string from the file
puts() Writes a string to the file
putw() Writes an integer to the file

File Concept by Dr. Rakesh Rathi 85


Function Operation
getw() Reads an integer from the file
fread() Reads structured data written by fwrite() function
fwrite() Writes block of structured data to the file
fseek() Sets the pointer position anywhere in the file
feof() Detects the end of file
ferror() Reports error occurred while read/write operations
perror() Prints compilers error messages along with user defined messages
ftell() Returns the current pointer position
rewind() Sets the record pointer at the beginning of the file
unlink() or Removes the specified file from the current directory
remove()
rename() Changes the name of the file

File Concept by Dr. Rakesh Rathi 86


1. Write a program to generate a data file containing the list of cricket players, no. of innings played, highest
run score and no. of hatriks made by them. Use structure variable to store the cricketer’s name, no. of
innings played, highest run score and the number of hatriks.
2. Write a program to reposition the file to its 10th character.

3. Write a program to display contents of file on the screen. The program should ask for file name. Display the
contents in capital case.
4. Write a program to find the size of the file.

5. Write a program to combine the contents of two files in a third file. Add line number at the beginning of
each line.
6. Write a program to display numbers form 1 to 100. Re-direct the output of the program to text file.

7. Write a program to write contents of one file in reverse into another file.

8. Write a program to interchange contents of two files.

File Concept by Dr. Rakesh Rathi 87


Q1. What is a file?
Ans. Organized collection of data is called a ‘file’. A file represents data which is arranged in a specific format and stored
on a secondary storage media like hard disk or CD.
Q2. What is file pointer? What is its use?
Ans. A file pointer represents the pointer to the beginning of a file. Using a file pointer, we can open a file or close the file.
Also, file pointer helps to move directly to any particular byte position in the file.
Q3. What is FILE?
Ans. FILE is a predefined datatype in the header file: stdio.h. A file pointer is defined using FILE datatype.
Q4. What are file open modes?
Ans. File open modes are strings which represent the purpose of opening a file. For example, “r” specifies read mode,
“w” specifies write mode and “a” specifies append mode. “r+” and “w+” specify read and write mode and “a+” specifies
read and append mode.

File Concept by Dr. Rakesh Rathi 88


Q5. What is the difference between text files and binary files?
Ans.
Text files Binary files
Text files store data in the form of Binary files store data in the form of
ASCII characters bits and bytes
Text files use more memory Binary files are more compact and
hence use less memory
Text files are used to store and Binary files can be used to create and
access normal text access normal text, images, audios
and videos
Special software is not required to Special software or plugins may be
view the text file. required to view the binary files

File Concept by Dr. Rakesh Rathi 89


Q6. What are formatted and unformatted text files?
Ans. A formatted text file stores characters and numbers also, but in text format. An unformatted text file stores
characters only.
Q7. How can you print program output on paper?
Ans. Using fprintf() function with ‘stdprn’ as first argument will send the output of a program to the printer so that it can be
printed on the paper.
Q8. What do you mean by random access files?
Ans. Random access files are the files whose data can be accessed randomly by moving the file pointer from one place
to another place in the file.
Random access files use fseek() to move the file pointer and ftell() to know the position of file pointer.

File Concept by Dr. Rakesh Rathi 90


File Concept by Dr. Rakesh Rathi 91
File Concept by Dr. Rakesh Rathi 92

You might also like