File Handling in C

Roadmap

‡ ‡ ‡ ‡ ‡ ‡

File File variable declaration File open and Close File read and write Pre-opened files Binary I/O

Files
A file is a collection of related data. C treats a file as a series of bytes. Many files reside on disk; however, devices like terminals, printers, and magnetic tapes are also considered files.

The C library contains a large number of routines for manipulating files. The declarations for the structures and functions used by the file functions are stored in the standard include file <stdio.h>. Before doing anything with files, you must put the line: #include <stdio.h>

How to open a file?
» Firstly it searches on the disk the file to be opened. » Then it loads the file from the disk into a place in memory called buffer. » It sets up a character pointer that points to the first character of the buffer.

File variable Declaration
The declaration for a file variable is: FILE *file-variable; /* comment */ For example: #include <stdio.h> FILE *in_file; /* file containing the input data */

Fopen() and Fclose()
Before a file can be used, it must be opened using the function fopen. fopen returns a pointer to the file structure for the file. The format for fopen is: file-variable = fopen(name, mode); where: file-variable is a file variable. A value of NULL is returned on error. name is the actual name of the file (data.txt, temp.dat, etc.).

‡ Mode indicates if the file is to be read or written. mode is "w" for writing and "r" for reading. The flag "b" can be added to indicate a binary file. Omitting the binary flag indicates an ASCII (text) file. Flags can be combined. So "wb" is used to write a binary file.

The fopen() function returns a file handle that will be used in subsequent I/O operations. If there is an I/O error, then the value NULL is returned:

Other modes
» "r" Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL. Operations possible ± reading from a file » "w" Searches file. If the file exists, its contents are overwritten. If the file doesn¶t exist, a new file is created. Returns NULL, if unable to open file. Operations possible ± writing to the file. » "a" Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn¶t exist, a new file is created. Returns NULL, if unable to open file. Operations possible - adding new contents at the end of file. » "r+" Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file. Operations possible reading existing contents, writing new contents, modifying existing contents of the file.

» "w+" Searches file. If the file exists, its contents are overwritten. If the file doesn¶t exist a new file is created. Returns NULL, if unable to open file. Operations possible writing new contents, reading them back and modifying existing contents of the file. » "a+" Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file doesn¶t exist, a new file is created. Returns NULL, if unable to open file. Operations possible reading existing contents, appending new contents to end of file. Cannot modify existing contents.

Example 1
FILE *in_file; /* File to read */ in_file = fopen("input.txt", "r"); /* Open the input file */ if (in_file == NULL) { /* Test for error */ fprintf(stderr, "Error: Unable to input file 'input.txt'\n"); exit (8); }

Closing a file
The function fclose will close the file. The format of fclose is: status = fclose(file-variable); fclose(file-variable); The variable status is zero if the fclose was successful or nonzero for an error. If you don't care about the status, the second form closes the file and discards the return value.

Pre-opened files
C provides three pre -opened files.

Fgetc() & Fputc()
The function fgetc reads a single character from a file. If no more data exists in the file, the function will return the constant EOF (EOF is defined in stdio.h ). ch = fgetc(file); Note that fgetc returns an integer, not a character. This return is necessary because the EOF flag must be a noncharacter value. A similar function, fputc , exists for writing a single character. fputc(character, file);

Example2
#include <stdio.h> const char FILE_NAME[] = "input.txt"; #include <stdlib.h> int main() { int count = 0; /* number of characters seen */ FILE *in_file; /* input file */ /* character or EOF flag from input */ int ch; in_file = fopen(FILE_NAME, "r"); if (in_file == NULL) { printf("Cannot open %s\n", FILE_NAME); exit(8); }

while (1) { ch = fgetc(in_file); if (ch == EOF) break; ++count; } printf("Number of characters in %s is %d\n", FILE_NAME, count); fclose(in_file); return (0); }

Fgets() and fputs()
The functions fgets and fputs work on one line at a time. The format of the fgets call is: string_ptr = fgets(string, size, file); ‡ fputs is similar to fgets except that it writes a string instead of reading it. The format of the fputs function is: string_ptr = fputs(string, file); The parameters to fputs are similar to the ones for fgets. fputs needs no size because it gets the size of the line to write from the length of the string. (It keeps writing until it hits a null, '\0'.)

where: string_ptr is equal to string if the read was successful, or NULL if end -of-file or an error is detected. string is a character array in which the function places the string. size is the size of the character array. fgets reads until it gets a line (complete with ending \n) or it reads size -1 characters. It then ends the string with a null (\0).

Problems can occur if the size specified is too big. C provides a convenient way of making sure that the size parameter is just right through the use of the sizeof operator. ‡ The sizeof operator returns the size of its argument in bytes.

For example: char string[100]; ... fgets(string, sizeof(string), in_file);

Fprintf()
The function fprintf converts data and writes it to a file. The general form of the fprintf function is: count = fprintf(file, format, parameter-1, parameter-2, ...); fprintf has two sister functions: printf and sprintf. sprintf is similar to fprintf, except that the first argument is a string.

where: count is the number of characters sent or -1 if an error occurred. format describes how the arguments are to be printed. parameter-1, parameter-2, ... are parameters to be converted and sent.

example3
#include <stdio.h> #include <stdlib.h> int main() { char name[100]; /* name of the file to use */ FILE *in_file; /* file for input */ printf("Name? "); Scanf(³%s´,&name); in_file = fopen(name, "r"); if (in_file == NULL) { fprintf(stderr, "Could not open file\n"); exit(8); } printf("File found\n"); fclose(in_file); return (0); }

Example4
int main() { int i; FILE *fout; int str[257]; for(i=0;i<256;i++) { str[i]=i; } fout = fopen("hex.txt", "w"); if (fout == (FILE *)0) exit(-1); i = 0; while (i != 256) { fprintf(fout,"%x\n",str[i] ); i++; }

example4
main() { int i = 10 ; char ch = 'A' ; float a = 3.14 ; char str[20] ; printf ( "\n%d %c %f", i, ch, a ) ; sprintf ( str, "%d %c %f", i, ch, a ) ; printf ( "\n%s", str ) ; } In this program the printf( ) prints out the values of i, ch and a on the screen, whereas sprintf( ) stores these values in the character array str.

Fscanf()
scanf has similar sister functions: fscanf and sscanf. The format for fscanf is: number = fscanf(file, format, &parameter-1, ...);

where: number is the number of parameters successfully converted. If there was input but nothing could be converted, a zero is returned. If no data is present, EOF is returned. file is a file opened for reading. format describes the data to be read. parameter-1 is the first parameter to be read.

Binary I/O
Binary I/O is accomplished through two routines: fread and fwrite. The syntax for fread is: read_size = fread(data_ptr, 1, size, file); fwrite has a calling sequence similar to fread: write_size = fwrite(data_ptr, 1, size, file);

where: read_size is the size of the data that was read. If this value is less than size, then an end-of-file or error was encountered. data_ptr is the pointer to the data to be read. This pointer must be cast to a character point (char *) if the data is any type other than a character. size is the number of bytes to be read. file is the input file.

‡ I request Electronics and communication ‡ ENGINEERING students to visit my blog for ‡ more«« ‡ abhishek1ek.blogspot.com ‡ awhengineering.blogspot.com

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer: Get 4 months of Scribd and The New York Times for just $1.87 per week!

Master Your Semester with a Special Offer from Scribd & The New York Times