Sie sind auf Seite 1von 57

File Handling inC

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.

Input Device Input stream


Program

Output Device Output stream


Three special streams
•Three special file streams are defined in the <stdio.h> header

–stdin reads input from the keyboard

–stdout send output to the screen

–stderr prints errors to an error device

fprintf (stdout,“C programming\n”);


What is a file?

• A file is a collection of related data that a computer


treats as a single unit.
• Computers store files to secondary storage so that the
contents of files remain intact when a computer shuts
down.
• When a computer reads a file, it copies the file from
the storage device to memory; when it writes to a file,
it transfers data from memory to the storage device.
What is aFile?
• C uses a structure called FILE (defined in stdio.h) to store
the attributes of a file.
• Typical operations on files:
–Open
–Read
–Write
–Close
• How is a file stored?
–Stored as sequence of bytes, logically contiguous
(may not be physically contiguous on disk).
What is a File(2)?
• The last byte of a file contains the end‐of‐file character
(EOF).
• While reading a text file, the EOF character can be checked
to know the end.
• Two kinds of files:
• Text :: contains ASCII codes only
• Binary :: can contain non‐ASCII characters
– Image, audio, video, executable, etc.
Why File?
• Some programs expect the same set of data to be fed as
input every time it is run.
– Cumbersome.
– Better if the data are kept in a file, and the program
reads from the file.
• Programs generating large volumes of output.
– Difficult to view on the screen.
– Better to store them in a file for later viewing/
processing
Various file operations

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

• 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)

from Table 7-1 in Forouzan & Gilberg, p. 400


More on File Open Modes

from Figure 7-4 in Forouzan & Gilberg, p. 401


Contd.
• Points to note:
– Several files may be opened at the same
time.
– For the “w” and “a” modes, if the named
file does not exist, it is automatically
created.
– For the “w” mode, if the named file exists,
its contents will be overwritten.
Additionally,
• r+ open for reading and writing,
start at beginning
• w+ open for reading and writing
(overwrite file)
• a+ open for reading and writing
(append if file exists)
File Open
• The file open function (fopen) serves two
purposes:
– It makes the connection between the physical file
and the stream.
– It creates “a program file structure to store the
information” C needs to process the file.
• Syntax:
filepointer=fopen(“filename”, “mode”);
More On fopen
• The file mode tells C how the program
will use the file.
• The filename indicates the system name
and location for the file.
• We assign the return value of fopen to
our pointer variable:
spData = fopen(“MYFILE.TXT”, “w”);
spData = fopen(“A:\\MYFILE.TXT”, “w”);
More On fopen
Opening a File
• A file must be “opened” before it can be used.
FILE *fp;
fp = fopen (filename, mode);
– fp is declared as a pointer to the data type FILE.
– filename is a string ‐ specifies the name of the file.
– fopen returns a pointer to the file which is used in all
subsequent file operations.
– mode is a string which specifies the purpose of opening
the file:
“r” :: open the file for reading only
“w” :: open the file for writing only
“a” :: open the file for appending data to it
Closing aFile
• When we finish with a mode, we need to close the file
before ending the program or beginning another mode
with that same file.

• To close a file, we use fclose and the pointer variable:


fclose(spData);
Closing a file
• Ensures
– All outstanding information associated with file
flushed out from buffers
– All links to file broken
– Accidental misuse of file prevented

• If want to change mode of file, then first close and


open again
Closing a file
Syntax: fclose(file_pointer);
Example:

FILE *p1, *p2;


p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1);
fclose(p2);
•pointer can be reused after closing
fprintf()
• similar to printf().
• in addition provide file‐pointer
Syntax:
fprintf (fp,"string",variables);

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

• 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);

fscanf returns EOF when end‐of‐file reached


Reading Data Using fscanf( )

•We also read data from a file using fscanf().

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

• 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

Function name Operation


fopen() •Creates a new file for use
•Opens an existing file for use

fclose() •Closes a file which has been opened for use

getc() •Reads a character from a file

putc() •Writes a character to a file

fprintf() •Writes a set of data values to a file.

fscanf() •Reads a set of data values from a file

getw() •Reads an integer from a file.

putw() •Writes an integer to a file


Character Input
Input/Output operations on files:
getc and putc functions
•The analogous to getchar() and putchar() function and handle one
character at a time.
getchar() function is used to get/read a character from keyboard input.
putchar() function is used to write a character on standard output/screen.

putc()
•Assume that a file is opened with mode w and file pointer fp1.

putc ( c, fp1 ) ;

•Writes the character contained in the character variable c to the file


associated with FILE pointer fp1.
getc()
•getc() is used to read a character from a file that has been
opened in read mode.
c = getc( fp2 );
•Reads a character the file whose file pointer is fp2.
/*PROGRAM FOR VARIOUS MODES IN FILE HANDLING */
#include<stdio.h> main()
{
FILE *f1;
char c;
printf("\nData input\n");
f1=fopen("TESTFILE.txt","w"); /*OPEN THE FILE INPUT*/
while((c=getchar())!=EOF) /*GET A CHARACTER FROM KEYBOARD*/
putc(c,f1); /*WRITE A CHARACTER TO THE FILE 'TESTFILE'*/
fclose(f1); /*CLOSE THE FILE 'TESTFILE'*/

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.

The general format:

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

Typical error situtations:


•Trying to read beyond the end-of-file marks.
•Device overflow
•Trying to use a file that has not been opened
•Trying to perform an operation on a file, when the file is opened
for another type of operation
•Opening a file with an invalid filename.
•Attempting to write to a write-protected file.
feof function:
•Used to test for end of file condition.
•It takes a FILE pointer as its only argument.
•Return a nonzero integer value if all of the data from the specified file
has been read.
•Otherwise returns zero.

if(feof(fp))
printf(“\nEnd of data\n”);

•fp : a pointer to file opened for reading


ferror function:
Reports the status of the file indicated
Takes a FILE pointer as its argument
Return a nonzero integer if an error has been detected upto that point.
Otherwise return zero.

if(ferror(fp))
printf (“An error has occurred”);

Print the error message, if the reading is not successful.


/*PROGRAM FOR ERROR HANDLING*/
#include<stdio.h> main()
{
FILE *fp;
int a[5], i=0, number;
fp=fopen("MAX.txt","w");
for(i=0;i<5;i++)
{
printf("\n Enter the elements into the file „MAX‟\n");
scanf("%d",&a[i]);
putw(a[i],fp);
}
fclose(fp);
fp=fopen("MAX.txt","r");
printf("\nContents of the file 'MAX'\n");
while((number=getw(fp))!=EOF)
{
printf("\n%d\n",number);
}

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

• In the text mode, a special character with the ASCII code 26 is


inserted at the end of the file. This character when
encountered returns the EOF signal to the program.
• This is not the case in binary mode. In the binary mode, we
do not have any special character to signify the EOF. It keeps
track with the help of the number of characters present in the
directory entry of the file.
Reading and writing in a BinaryFile

• A Binary file is similar to the text file, but it contains only


large numerical data. The Opening modes are mentioned in
the table on the next slide.

• fread() and fwrite() functions are used to read and write in


a binary file.
Modes
• rb ‐ open a binary‐file in read‐mode, set the pointer to the
beginning of the file.
• wb ‐ open a binary‐file in write‐mode, set the pointer to the
beginning of the file.
• ab ‐ open a binary‐file in write‐mode, set the pointer to the end
of the file.
• r+b ‐ open a binary‐file in read/write‐mode, if the file does not
exist, it will not be created.
• w+b ‐ open a binary‐file in read/write‐mode, set the pointer to
the beginning of the file.
• a+b ‐ open a binary‐file in read/append mode.
Binary File I/O
• The declarations for each are similar:
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE
*a_file);
– the declaration of a void *ptr; void means that it is a pointer that can be
used for any type variable.
– The first argument is the name of the array or the address of the structure
you want to write to the file.
– The second argument is the size of each element of the array; it is in bytes.
For example, if you have an array of characters, you would want to read it
in one byte chunks, so size_of_elements is one. You can use the sizeof
operator to get the size of the various datatypes;
– for example, if you have a variable
• int x; you can get the size of x with sizeof(x);.
• This usage works even for structs or arrays. Eg, if you have a variable of
a struct type with the name a_struct, you can use sizeof(a_struct) to
find out how much memory it is taking up.
e.g., sizeof(int);
fread ()
Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

Remarks:
fread reads a specified number of equal‐sized data items
from an input stream into a block.

ptr = Points to a block into which data is read


size = Length of each item read, in bytes
n = Number of itemsread
stream = filepointer
Example
#include <stdio.h> int main()
{
FILE *f;
char buffer[11];
if (f = fopen("fred.dat", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:\n%s\n", buffer);
}
return 0;
}
fwrite()
Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);

Remarks:
fwrite appends a specified number of equal‐sized data items to an output file.

ptr = Pointer to any object; the data written begins at ptr


size = Length of each item of data
n =Number of data items to be appended stream = file pointer
Example
Example:
#include <stdio.h> int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.dat","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}
Homework
• Program to Reverse the Contents of a
File and print it

Das könnte Ihnen auch gefallen