Showing posts with label 10. DATA FILES. Show all posts
Showing posts with label 10. DATA FILES. Show all posts

Tuesday, January 12, 2010

10.5 CONCEPT OF BINARY FILES

So far we have discussed mostly about data files (commonly known as text files).Every computer uses another kind of files also that are known as binary files. All machine language files are actually binary files.For opening a binary file, file has to be mentioned as "rb" or "wb" in fopen command. Otherwise all files are opened in default mode, which is the text mode. So mentioning mode as "r" or "w" in fopen is always equivalent to "rt" or "wt" respectively. Here t stands for text (files) and b stand for binary (files).It may be noted that text files can also be stored and processed as binary files but not vice-versa.The binary files differ from text files in two ways mainly:
1.The storage of newline characters
2. The eof character

First difference is about the storage of \n, i.e. newline character. In text files, \n is stored as a single newline character by user, but it takes 2 bytes of storage inside the memory. Are you surprised? Actually newline characters is collection of two characters- first carriage return(\r, ASCII code 13), and second line feed(ASCII code 10). When a text file \n, it is stored using 2 bytes, but is considered as a single character. So when you try to count the number of characters of a text file, each newline character contributes by one.

Text files and binary files also differ in the way of handling end of file. Although this may not make much difference to the users, but it may become a reason of failure of certain programs.Hence, this difference is crucial to understand.The eof corresponds to the character having ASCII code 26 for text files only. In binary files there is no such explicit eof character. The binary files do not store any special character at the end of file  and their file-end is verified by using their size itself.Now if a text file is opened in binary mode for reading purposes, it may detect eof wrongly as a result of a particular data having ASCII code 26.

While discussing binary files, one more point is worth mentioning  and corresponds to storage of data in binary format. The numbers can be written to files using fprintf statement (putc and fputc can't be used for this purpose).The fprintf statements stores numbers as sequence of alphabets. So storage of 1001 in files (text as well as binary) using fprintf will be done as sequence of 4 alphabets '1', '0', '0', '1'. It means that storage of a 4-digit number will take 4 bytes. But on a 16-bit computer, an integer needs 2 bytes of storage and this concept can be utilized with help of fwrite statement (in both text as well as binary mode). The fwrite will store every integer value by taking two bytes not equal to the number of digits in that integer value.

Let us write a C program which stores numbers in binary format using fwrite.

/* store 1001 to 1100 in a binary file using fwrite */


#include < stdio.h >
#include < conio.h >


main()
{
FILE *fp;
int i;
if ((fp = fopen("binval.dat", "wb")) == NULL)
  printf("\n ERROR- Cannot create the designated file\n");
else  {
    for  (i=1001; i <= 1100; i++)
      fwrite (&i, sizeof (int), 1, fp);

}
fclose(fp);
getch();

}

The size of the output file created with the help of the above program will be 200 bytes (2 bytes for each of 1000 integers). If the same data was to be stored in a text file using fprintf statement, the size of the file would be minimum 4000 bytes (4 x 1000).

Monday, January 11, 2010

10.4 UNFORMATTED DATA FILES

Some applications involve the use of data files to store blocks of data, where each block consists of a fixed number of contiguous bytes. Each block will generally represent a complex data structure, such as a structure or an array.For example, a data file may consist of multiple structures having the same composition, or it may contain multiple arrays of the same type and size. For such applications it may be desirable to read the entire block from the data file, or write the entire block to the data file, rather than reading or writing the individual components (i.e. structure members or array elements) within each block separately.

The library function fread and fwrite are used in this kind of situations. These functions are often referred to as unformatted read and write functions.Similarly, data files of this type are often referred to as unformatted data files.

Each of these functions require four arguments: a pointer to the data block, the size of the data block, the number of data blocks being transferred, and the stream pointer. Thus a typical fwrite function can be written as

   fwrite (&customer, sizeof (record), 1, fpt);

where customer is a structure variable of type record, and fpt is the stream pointer associated with a data file that has been opened for output.

Sunday, January 10, 2010

10.3 READING AND WRITING A DATA FILE

Files are generally  used for two purposes- reading and writing. Whenever we want to store something into a file, the file needs to be opened in write mode. If the contents to be stored in the output file are already known then the then the file can also be created directly using a text editor or word processor. In that case the file is obviously a formatted stream-oriented data file. However, if the contents to be stored are not pre-defined and are computed generated with the help of a program itself. then the output file can be created with help of a program only.

The following program reads all the numbers from the input file values.dat and stores average of these numbers in an output file named as average.res

#include < stdio.h >
#include < conio.h >


main()
{
FILE *fpin, *fpout;
float val, avg, sum=0;
int count=0;


if ((fpin = fopen("values.dat", "r"))== NULL)
   /*open the data file for reading purposes*/
  printf("\nERROR - cannot open the designated file\n");

else  {/*read and display each character from the file*/
   while(!feof(fpin))  {
fscanf(fpin, "%f", &val);
sum += val;
count++;

}
}
avg = sum/count;
if ((fpout = fopen("average.res", "w")) == NULL)
   /*open the data file for writing purposes*/
  printf("\nERROR- cannot open the designated file\n");
else  /*write the average in the file*/
  fprintf(fpout, "The average of numbers of file values.dat is %.3f\n", avg);


fclose(fpin);
fclose(fout);
getch();


}

If the average value computed is 81.563, then the output line will have the following line

The average of numbers of file values.dat is 81.563

10.2 OPENING AND CLOSING A DATA FILE

When working with a stream-oriented data file, the first step is to establish a buffer area,where information is temporarily stored while being transferred between the computer's memory and the data file.The buffer area allows information to be read from or written to the data file more rapidly than would otherwise be possible.

The buffer area is established by writing

FILE  *ptvar;

where FILE (uppercase letters required) is a special structure type that establishes the buffer area, ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type FILE is defined within a system include file, typically stdio.h. The pointer ptvar is often referred to as a stream pointer, or simply a stream.

A data file must be opened before it can be created or processed.this associates the file name with the buffer area (i.e.with the stream). It also specifies how the data file will be utilized, i.e. as a read only file, a write-only file, or a read/write file,in which both operations are permitted.

The library function fopen is used to open a file.This function is typically written as

ptvar = fopen (file-name, file-type);

where file-name and file-type are strings that represent the name of  the data file and the manner in which the data file will be utilized. The name chosen for the file-name must be consistent with the rules for naming files, as determined by the computer's operating system.The file-type must be one of the strings shown in the following table.



File-Type

Meaning

"r"
Open an existing file for reading only.

"w"
Open a new file for writing only. If a file with the
specified file-name currently exists, it will be destroyed and a
new-file created in its place.

"a"
Open an existing file for appending (i.e., for adding the
information at the end of the file). A new file will be created if the
file with the specified file-name does not exist.

"r+"
Open an existing file for both reading and writing.

"w+"
Open a new file for both reading and writing. If a file with
the specified file-name currently exists, it will be destroyed and
a new file will be created in its place.

"a+"
Open an existing file for both reading and appending. A new
file will be created if the file with the specified file-name does
not exist.

Finally a file must be closed at the end of the program.This can be acomplished with the library function fclose. The syntax is simply

fclose (ptvar);

It is good programming practice to close a data file explicitly using the fclose function, though most C compilers will automatically close a data file at the end of a program execution.

Saturday, January 9, 2010

10.1 WHY FILES

There can be many reasons to use files.The first and foremost reason is need of permanency of storage of data.If we want to preserve the output of any program for future use, it is not possible without files.All messages or values printed with help of any output statements like printf, putchar, etc. are never available for future use and the only solution in that case is to write the output in files.Similarly, if there is a large amount of data generated as output by a program, storing that output in file will help in easy handling/analysis of the output, as user can see the whole output at any time even after complete execution of the program.

The above situations explain the need of output files.The input files are also equally important and useful.if a program needs a lot of data to be inputted, user cannot keep on typing again and again for repeated execution of the program.In that case, all input data can be once written in a file and then that file can be easily used as the input file.moreover the transfer of input-data and/or output-data from one computer to another can be easily done by using files.

Friday, January 8, 2010

10. DATA FILES

Many applications require that information be written to or read from an auxiliary device.Such information is stored on the memory device in the form of a data file. Thus data files allow us to store information permanently, and to access and alter information whenever necessary.

There are two different types of data files, called stream-oriented (or standard access) data files, and system-oriented (or low-level) data files.Stream oriented data files are generally easier to work with and are therefore commonly used.

Stream-oriented data files van be subdivided into  two categories - they are text files and unformatted data files.Text files consist of consecutive characters.These characters can be interpreted as individual data items, or as components of strings or numbers.Unformatted data files organizes data into blocks containing contiguous bytes of information.These blocks represent more complex data structures, such as arrays and structures.


System-oriented data files are more closely related to the computer's memory system than stream oriented data files. They are more complicated to work with, though their use may be more efficient for certain kinds of applications.

Data files are most frequently used to store user's data. However data related to numbers can be efficiently stored in binary files, which are also useful to hanle file containing machine language contents e.g. exe or .com files.The files which are stored in binary format differ significantly from data (also called as text) files.

In this chapter we are only concerned with stream oriented-data files.