Users Online
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Latest Articles
Articles Hierarchy
#C PROGRAMMING LANGUAGE TUTORIALS
Files Handling - C Programming
1. File Pointers
There are many ways to use files in C. The most straight forward use of files is via a file pointer.
FILE *fp;
fp
is a pointer to a file.
The type FILE
, is not a basic type, instead it is defined in the header file stdio.h
, this file must be included in your program.
2. Opening a File
fp = fopen(filename, mode);
The filename and mode are both strings.
The mode can be
r
- readw
- write, overwrite file if it ex istsa
- write, but append instead of overwriter+
- read & write, do not destroy file if it existsw+
- read & write, but overwrite file if it existsa+
- read & write, but append instead of overwriteb
- may be appended to any of the above to force the file to be opened in binary mode rather than text modefp = fopen("data.dat","a");
- will open the disk file data.dat for writing, and any information written will be appended to the file.
The following useful table from the ANSI C Rationale lists the different actions and requirements of the different modes for opening a file:
fopen
returns NULL
if the file could not be opened in the mode requested. The returned value should be checked before any attempt is made to access the file. The following code shows how the value returned by fopen might be checked. When the file cannot be opened a suitable error message is printed and the program halted. In most situations this would be inappropriate, instead the user should be given the chance of re-entering the file name.
#include <stdio.h>
int main()
{
char filename[80];
FILE *fp;
printf("File to be opened? ");
scanf("%79s", filename);
fp = fopen(filename,"r");
if (fp == NULL)
{
fpri ntf(stderr, "Unable to open file %s\n", filename);
return 1; /* Exit to operating system */
}
//code that accesses the contents of the file
return 0;
}
Sequential file access is performed with the following library functions.
fprintf(fp, formatstring , ...)
- print to a filefscanf(fp, formatstring , ...)
- read from a filegetc(fp)
- get a character from a fileputc(c, fp)
- put a character in a fileungetc(c, fp)
- put a character back onto a file (only one character is guaranteed to be able to be pushed back)fopen( filename , mode)
- open a filefclose(fp)
- close a file
The standard header file stdio.h defines three file pointer constants, stdin
,stdout
and stderr
for the standard input, output and error streams. It is considered good practice to write error messages to the standard error stream.
Use the fprintf()
function to do this:
fprintf(stderr,"ERROR: unable to open file %s\n", filename);
The functions fscanf()
and getc()
are used for sequential access to the file, that is subsequent reads will read the data following the data just read, and eventually you will reach the end of the file. If you want to move forwards and backwards through the file, or jump to a specific offset from the beginning, end or current location use the fseek()
function (though the file mustbe opened in binary mode). The function ftell()
reports the current offset from the beginning of the file.
If you wish to mix reading and writing to the same file, each switch from reading to writing (or vice versa) mustbe preceded by a call to fseek()
, fsetpos()
, rewind()
or fflush()
. If it is required to stay at the same position in the file then use fflush()
or fseek(fp,0L,SEEK_CUR)
which will move 0 bytes from the current position!
3. Examples
EXAMPLE STATEMENT FOR FILES HANDLING IN C LANGUAGE |
---|
1. Illustrate as to how the data stored on the disk is read
|
2. Write static data in file and read from file |
/**********************************************************
Statement - Write static data in file and read from file
Programmer - Vineet Choudhary
Written For - http://developerinsider.co
**********************************************************/
#include<stdio.h>
#include<conio.h>
struct Student {
int roll;
char name[12];
int percent;
} s1 = { 96, "VINEET", 76 };
void main() {
FILE *fp;
struct Student s2;
clrscr();
//Write details of s1 to file
fp = fopen("ip.txt", "w");
fwrite(&s1, sizeof(s1), 1, fp);
fclose(fp);
//Read saved details from file
fp = fopen("ip.txt", "r");
fread(&s2, sizeof(s2), 1, fp);
fclose(fp);
printf("\nRoll : %d", s2.roll);
printf("\nName : %s", s2.name);
printf("\nPercent : %d", s2.percent);
getch();
}