File Handling
File Handling
File Handling
Streams
• Stream is a sequence of bytes.
• It is a logical device either produces or consumes information.
• Interface between a program and I/O device. It is linked to a
physical device by the I/O system.
1) naming a file
2) opening a file
3) reading data from a file
4) writing data to a file
5) closing a file.
Steps in Processing aFile
1. Create the stream via a pointer variable using the FILE structure:
FILE *p;
2. Open the file, associating the stream name with file name.
3. Read or write the data.
4. Close the file.
The basic file operations are
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
Writing to a file using fprintf( )
• fprintf() works just like printf except that its first argument is a file
pointer.
FILE *fptr;
fptr = fopen ("file.dat","w");
fprintf (fptr, "Hello World!\n");
18
Example
/*Addtwo numbers using file handling*/
void main()
{
FILE *fp;
int a,b,c;
a = 10;
b = 20;
fp=fopen("op.txt","w"); //Open File in Write Mode
c=a+b;
fprintf(fp,"nSum of %d and %d is %d",a,b,c);
}
fprintf() Example
#include <stdio.h>
int main()
{
FILE *fp;
char name[10];
double balance;
int account;
if ((fp = fopen(“clients.dat”, “w”)) == NULL)
{
printf(“File could not be opened\n”);
}
else
{
printf(“Enter one account, name, and balance.\n”);
scanf(“%d%s%lf”, &account, name, &balance);
fprintf(fp, "%d %s %.2f\n", account, name, balance);
fclose(fp);
}
return 0;
}
Exercise
FILE *fptr;
fptr = fopen (“input.dat”, “r”);
/* Check it's open */
if (fptr == NULL)
{
printf(“Error in opening file \n”);
}
fscanf (fptr, “%d %d”, &x, &y);
20
Text Files – read from a file
#include <stdio.h>
int main()
{
FILE *fp;
char name[10];
double balance;
int account;
if ((fp = fopen(“clients.dat”, “r”)) == NULL) {
printf(“File could not be opened\n”);
}
else {
fscanf(fp, “%d%s%lf”, &account, name, &balance);
printf("%d %s %.2f\n", account, name, balance);
fclose(fp);
}
return 0;
}
Exercise
putc()
•Assume that a file is opened with mode w and file pointer fp1.
putc ( c, fp1 ) ;
printf("\nData output\n");
f1=fopen("TESTFILE.txt","r"); /*REOPEN THE FILE 'TESTFILE'*/
putw(integer,fp);
getw(fp);
/*PROGRAM FOR HANDLING OF INTEGER DATA FILES*/
#include<stdio.h>
void main()
{
FILE *f1;
int number, i;
printf("\ncontents of DATA file\n");
f1=fopen("DATA.txt","w"); /*create DATA.txt file*/
for(i=0;i<=30;i++)
{
scanf("%d",&number);
if(number == -1 )
break;
putw(number,f1); /*Write the integer value to file 'fl'*/
}
fclose(f1);
f1=fopen("DATA.txt","r");
printf("\ncontents of DATA file\n");
while((number = getw(f1))! =EOF) /*read the integer value from file 'f1'*/
printf("\n%d", number);
fclose(f1);
}
Output:
contents of DATA file
111 222 333 444 555 -1
contents of DATA file 111 222 333 444 555
ERROR HANDLING DURING I/O
OPERATIONS
if(feof(fp))
printf(“\nEnd of data\n”);
if(ferror(fp))
printf (“An error has occurred”);
if(feof(fp))
printf("\nEnd of data\n");
fclose(fp);
}
Output:
Enter the elements into the file “MAX.txt”
1
2
3
4
5
Contents of the file 'MAX.txt'
1
2
3
4
5
End of Data
Text File vs Binary File
• A text file stores data in the form of alphabets, digits and other special
symbols by storing their ASCII values and are in a human readable
format. For example, any file with a .txt, .c, etc extension. Whereas, a
binary file contains a sequence or a collection of bytes which are not
in a human readable format. For example, files with .exe, .mp3, etc
extension. It represents custom data.
• Now, when it comes to programming there are three major
differences between the two, i.e., Handling of newlines, storage of
numbers and representation of EOF(End of File).
Handling of Newlines
• Newline is the end of the line or line ending or line break. It is usually a
special character which signifies the end of the line. A newline
character in a text file is first converted into a carriage return-linefeed
combination and then written to the disk. Similarly, when read by a
text file the carriage return-linefeed combination is converted into a
newline. However, in a binary file, no such conversions take place.
Storage of Numbers
• In the text mode, the function fprintf() is used to store numerical data
in the disk. The texts and the characters are stored one character per
byte as it should be (char occupies 1 byte in the memory) and as
expected the integers should occupy 4 bytes(depends on the compiler)
per number. But this is not the case. For example, we have a number
567392. According to integer storage convention, it should occupy 4
bytes in the disk but it does not. It occupies 6 bytes,i.e., 1 byte for
every digit in the number. Thus, we see that each digit in the file is
treated as a character in itself and occupies more space than
necessary.
• This problem can be solved by using binary files. We should open the
file in binary mode(using “wb” or “rb” for write and read mode
respectively). The, using the function fread() or fwrite() we can easily
store the data in the binary form which shall use only 4 bytes for
storing the integer data.
Representation of EOF
Remarks:
fread reads a specified number of equal‐sized data items
from an input stream into a block.
Remarks:
fwrite appends a specified number of equal‐sized data items to an output file.