File handling in c

From GluCki
Jump to: navigation, search

We store information in files for many purposes, like data processing by our programs.

What is a File?

Abstractly, a file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. The meaning attached to a particular file is determined entirely by the data structures and operations used by a program to process the file.A file is simply a machine decipherable storage media where programs and data are stored for machine usage. Essentially there are two kinds of files that programmers deal with text files and binary files. These two classes of files will be discussed in the following sections :-

ASCII Text files

A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time. Similarly, since text files only process characters, they can only read or write data one character at a time.

Binary files

A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two essential differences. 1.No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed. 2.C Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer. Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques. They a generally processed using read and write operations simultaneously.

Creating a file and output some data

The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. Before we can write to a file, we must open it. We do this with the fopen() function. The file name is any valid DOS file name. It is enclosed in double quotes.

/* Program to create a file and write some data the file */

#include <stdio.h>
main( ) 
{
   FILE *fp;
   char stuff[25];
   int index;
   fp = fopen("TENLINES.TXT","w"); /* open for writing */
   strcpy(stuff,"This is an example line.");
   for (index = 1; index <= 10; index++)
   	fprintf(fp,"%s Line number %d\n", stuff, index);
   fclose(fp); /* close the file before ending program */
}

Reading (r)

When an r is used, the file is opened for reading, a w is used to indicate a file to be used for writing, and an a indicates that you desire to append additional data to the data already in an existing file.Using the r indicates that the file is assumed to be a text file. Opening a file for reading requires that the file already exist.If it does not exist, the file pointer will be set to NULL and can be checked by the program. Here is a small program that reads a file and display its contents on screen.

/* Program to display the contents of a file on screen */

#include <stdio.h>
void main() {
 FILE *fopen(), *fp;
 int c;
 fp = fopen("prog.c","r");
 c = getc(fp) ;
 while (c!= EOF)
 {
 		putchar(c);
c = getc(fp);
 }
 fclose(fp);
}

Writing (w)

When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file. Here is the program to create a file and write some data into the file.

#include <stdio.h>
int main() 
{
FILE *fp;
file = fopen("file.txt","w");
/*Create a file and add text*/
fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
fclose(fp); /*done!*/
return 0;
}

Appending (a)

When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file. Here is a program that will add text to a file which already exists and there is some text in the file.

#include <stdio.h>
int main() {
  FILE *fp
  file = fopen("file.txt","a");
  fprintf(fp,"%s","This is just an example :)"); /*append some text*/
  fclose(fp);
  return 0;
}

Outputting to the file The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard output device. The only real differences are the new function names and the addition of the file pointer as one of the function arguments. In the example program, fprintf replaces our familiar printf function name.

Closing a file

To close a file you simply use the function fclose with the file pointer in the parentheses.

 #include <stdio.h>
 main( )
 {
   FILE *fp;
   char c;
   funny = fopen("TENLINES.TXT", "r");
   if (fp == NULL)
 printf("File doesn't exist\n");
   else {
    do {
     c = getc(fp); /* get one character from the file
     */
       putchar(c); /* display it on the monitor
     */
     } while (c != EOF); /* repeat until EOF (end of file)
   */
   }
  fclose(fp);
 }

In this program we check to see that the file exists, and if it does, we execute the main body of the program. If it doesn’t, we print a message and quit. If the file does not exist, the system will set the pointer equal to NULL which we can test. The main body of the program is one do while loop in which a single character is read from the file and output to the monitor until an EOF (end of file) is detected from the input file. The file is then closed and the program is terminated.