Professional Documents
Culture Documents
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 a File
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
• fopen ‐ open a file‐ specify how its opened
(read/write) and type (binary/text)
• fclose ‐ close an opened file
• fread ‐ read from a file
• fwrite ‐ write to a file
File Open Modes
(1)
Example:
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
Exampl
/*Add two numbers using file
e
handling*/
void main()
{ FILE *fp;
int a,b,c;
a = 10;
b = 20;
fp=fopen("op.txt","w"); // Open File in Write
c=a+b; Mode
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;
}
Exerci
se
• WAP in C to input a list of names from
user and do the following:
– Write these names into a file
void main() {
FILE *fptr;
char name[20];
int age;
float salary;
fptr = fopen("emp.txt", "w"); /* open for writing
if (fptr == NULL) { */
printf("File does not exists \n");
return; }
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n”, name);
printf(
" Enter the age\n
" );
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);
fclose(fptr);
}
fscanf
• similar to scanf()
()
• in addition provide file‐pointer
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",&i);
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;
}
Exerci
se
• WAP in C to input a list of names from
user and do the following:
– Write these names into a file /*fprintf*/
– Read this list of names from the file and sort
them alphabetically
/* Read records from file */ fscanf( fpPtr, "%s", name );
Reading and Writing from File using fprintf() and fscanf()
struct emp using structures
{ char
name[10];
int age; };
void main() {
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while( !feof(q) )
getch();
}
High level I/O functions
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'*/
while((c=getc(f1))!=EOF) /*READ A CHARACTER FROM 'TESTFILE'*/
printf("%c",c);
/*DISPLAY A CHARACTER ON SCREEN*/
fclose(f1);
}
/*CLOSE THE FILE 'TESTFILE'*/
getw and putw functions
(Integer values)
•The getw and putw are integer-oriented functions.
•Deals with integer data only.
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");
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.