Professional Documents
Culture Documents
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.
We arrange the available data in a specific format and then store it in the form of a file.
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.
This function accepts ‘filename’ and ‘open mode’ in which to open the file.
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.
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;
}
Once a file is opened but not closed, then the data of the file may be corrupted or deleted.
fclose(fp);
Here, the file pointed by the pointer ‘fp’ is closed.
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.
If we want to read the last record of the file then it is expected to read all the records before it.
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.
For example:
If we want to read the last record of a file, we can directly read the same record.
Types of files
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.
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>.
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.
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.
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.
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.
fputs(str, fp);
To read a string from a file, we can use fgets() function.
When we reach the end of the file, we will get a NULL string.
OUTPUT
OUTPUT
These files are useful just to store characters and retrieve them.
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.
rewind(fp);
OUTPUT
OUTPUT
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.
This means one structure data is written as one record into the binary file.
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.
It reads the records from the binary file, generally one record at a time.
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.
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.
OUTPUT
But in many cases, it is advisable to take a printout of the report on a paper for further reference.
Write ‘stdprn’ in place of ‘stdout’ in the whole program to take printout of the output.
We want to store the report in another file so that it can be printed or viewed whenever needed.
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”);
OUTPUT
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.
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.
It returns non-zero if the file pointer is at the end of file, otherwise it returns zero.
#include<stdio.h> c=getc(fp);
#include<conio.h> }
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
First, position the file pointer at the end of the file using fseek().
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.
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
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);
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.
{ fp = fopen(“bank.dat”, “r+b”);
float balance; {
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.
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.
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.
ret_code = findnext(&file);
The reason may be that the mode of reading or writing operation may not be correct.
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.
OUTPUT
rewind():
This function resets the file pointer at the beginning of the file.
OUTPUT
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.
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’.
Closing a file:
The close() function closes the file.
This function is defined in ‘io.h’ header file.
OUTPUT
OUTPUT
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.