File Handling in c
File Handling in c
review
Introduction
Files are places where data can be stored
permanently.
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
Introduction
Data files
When you use a file to store data for use by a
programs
Are used for permanent storage of large
amounts of data
Storage of data in variables and arrays is only
temporary
Opening a file
Reading data from a file
Writing data to a file
Closing a file
w - open a file in write-mode, set the pointer to the beginning of the file.
a - open a file in write-mode, set the pointer to the end of the file.
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+ - open a file in read/write-mode, if the file does not exist, it will not be created.
w+ - open a file in read/write-mode, set the pointer to the beginning of the file.
a+ - open a file in read/append mode.
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.
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.
FILE *empl ;
char filename[25];
scanf (“%s”, filename);
empl = fopen (filename, “r”) ;
int main()
{
FILE *fp;
struct prod {
int cat_num;
float cost;
};
typedef struct prod product;
#include <stdio.h>
int main()
{ FILE *fileA, /* first input file */
*fileB, /* second input file */
*fileC; /* output file to be created */
int num1, /* number to be read from first file */
num2; /* number to be read from second file */
int f1, f2;
/* close files */
fclose(fileA);
fclose(fileB);
fclose(fileC);
return 0;
} /* end of main */