A file is a place on the disk where a group of related date is stored. Some basic file operation can be given as :
§  naming a file
§  opening a file
§  reading data from a file
§  writing data to a file
§  closing a file

Opening and closing a data file :

When working with a file steps it to establish a buffer area, where information is temporarily stored while being transferred between the computer’s memory and the data file. This buffer area allows information to be read from or written to the data file more rapidly then would otherwise be possible. The buffer area is established by writing

                        FILE *ptvar;

Where FILE (uppercase required) is a special structure type that establishes the buffer area and ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type file is defined with a system include file : typically stdio.h

A data file must be opened or created before it can be created or processed. Thus associates the file name with the buffer area. It also specifies how  the data file will be utilized. That is 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 represents the name of the data file and the manner in which the data  file will be utilized, respectively. The name chosen for the file_name must be consistent within 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 the file with specified file_name currently exists it will be destroyed and new file is created in its place.
“a”                                          open an existing file for appending. A new file will be created if the file with the specific 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 is created in its place.
“a+”                                        open an existing file for reading and writing. A new file will be created if the file with the specified file_name does not exist.

The fopen function returns a pointer to the beginning of the buffer area associated
with the file. A NULL value is returned if the file cannot be opened as for
example, when and existing file cannot be found. Finally a data file must be
closed at eh end of  the program. This ensures that all outstanding information
associated with the file is flushed out from the buffers and all links to the file are
broken. It also prevents any accidental misuse of the file. In case there is a limit to
the number of files that can be kept open simultaneously, closing of unwanted file
might help open the required files. Another instance, where we have to close a file
is when we want to reopen the same file in a different mode. This can be
accomplished with the library function fclose. The syntax is simply :


Text Box: #include <stdio.h>
FILE *fpt;


Input-output operation on file :


The simplest file i/o functions are fgetc and fputc. These are used to handle one character at a time. Assume that a file is opened with mode w and file point fpt. Then, the statement
Writes the character contained in the character variable c to the file associated with FILE pointer fpt. Similarly getc is used to read character from a file that has been opened in read mode. For example, the statement
                        C = fgetc(fp2);
Would read character from file whose file pointer is fp2. the file pointer moves by one character position for every operation of getc and putc. The getc will have been reached. Therefore, the reading should be terminated when EOF is encountered.

For example,

Text Box: Main()	
	FILE *fp;
	Char c;	
	Fp = fopen(“input”, “w”);
	While(c=getchar()) != EOF)
	f1 = fopen(“input”,”r”);
	while(c=fgetc(f1)) != EOF)


These functions are used to handle a string at a time. Assume that a file is open in the write mode and file pointer is fp1, then the statement
Writes the string contained in the character arrays to the file associated with FILE pointer fp1. similarly, fgets is used to read a string of particular length from a file that has been opened in read mode. For example,
Text Box: #include<stdio.h>
	FILE *fp;
	Char c[80];
	Fp = fopen(“INPUT”, “w”);
		fputc(“\n”, c);
fclose(fp) ;
fp = fopen(« INPUT », « r ») ;
while(gets(c,79, fp) = NULL)
printf(“%s \n”,c);

Would read string of 79 character from the file whose file pointer is fp1. The fgets will return NULL character when reached at the end of file. Therefore the reading should be terminated when NULL is encountered. For example,


These functions are used to read or write in formatted from from/to the files. The general form of fprintf is
            Fprintf(f1, “%s%d%function”, name, age, 7.5);

Here f1 is the file pointer name is an array variable of type character, age is integer variable.
The general form of fcanf is :
Fscanf(fp, “control string”, list);

This statement would cause the reading of the items in the list from the file specified by fp, according to the specifications contained in the control string. For example,

            Fcanf(f2, “%s” “%d” ”%f”, item, qty,price);
Fcanf returns the number of items that are successfully read. When the end of the file is reached, it returns the value of EOF.



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 complete data structure, such as a structure or an array. for such applications it may be desirable to read the entire block from the data file or write the entire block to the file.

The library function fread and fwrite are intended to be used in situations of this size of the data block, the number of data block being transferred and file pointer. thus typical fwrite and fread functions :
                        Fwrite(&customer, sizeof(record),1,fpt);
                        Fread(&customer, sizeof(record),1,fpt)
Where customer is a structure variable of type record and fpt is the file pointer associated with the data file that has been opened for input/output. Once an unformatted data file has been created with fwrite, it can be read with fread function. The function returns a zero value if an end-of-file condition has been detected and non-zero value if an end-of-file is not detected. Hence, a program that reads an unformatted data file can be reading file, as long as the value returned by fread is non-zero value.



There are occasions however, when we are interested in accessing only a particular part of a file and not in reading the other parts. This can be achieved with the help of the function fseek, ftell and rewind available in the library.

ftell :

ftell take a file pointer and returns a number of type long that corresponds to the current portion. This function is useful in saving the current position of a file, which can be used in the program. It takes the following form.
N =ftell(fp);
N would give the relative offset (n bytes) of the current position. This  means that n bytes have already bean read.

rewind :

rewind takes a file pointer and resets the position to the start of the file. For example the statement :
Would assign to fp because the file position has been set to the start of the file by rewind. This function helps us in reading a file more than once. Without having to close and open the file.

fseek :
 fseek function is used to move the position to a desired location within the file. It takes the following form.
            Fseek(fpt, offset, position)
Fpt is a pointer to file concerned. Offset is a number of variable of type long and position is an integer number. The offset specifies the number of bytes(position) to be moved from the location specified by position. The position can take one of the following three values :

0                    beginning of file
1                    current position
2                    end of file
The offset may be positive, meaning move forward and negative, meaning move backwards.
When the operation is successful, fseek returns a zero. If we attempt to move beyond the file boundaries and error occurs and fseek returns.






















The process of allocating memory at run time is known as dynamic memory allocation. malloc() and calloc() are library routines known as “Memory Management Functions” that can be used for allocating and freeing memory during program execution.


A block of memory may be allocated using the function malloc(). The function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. it takes the following form.
Ptr = (cast_type *) malloc(byte_size)
Ptr is a pointer of type cast_type. The malloc returns a pointer of cast_type to an area of memory of size byte_size. For example,
X = (int *) malloc(100*sizeof(int));
On successful execution of this statement a memory space equivalent to “100 times for the size of int” bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer x of type int. Similarly statement
            Cptr = (char *) malloc(10);
Allocates 10 byte of space for the cptr of type char. We may also use malloc to allocate space for complex data types such as structures. For example,
            Stptr = (struct store*)malloc(sizeof(struct store));
Where stptr is pointer of type struct store. The malloc allocates a block of contiguous bytes. The allocation can fall if the space in the heap is not sufficient to satisfy the request. If it fails it returns a NULL.


Calloc is memory allocation function that is normally used for requesting memory space at runtime for storing derived data types such as arrays and structures. Calloc allocates multiple block of storage, each of the same size and then sets all bytes to zero. The general form of calloc is ;
            Ptr = (cast_type *) calloc(n,elem_size);
The above statement allocates contiguous space of n blocks. Each of size elem_size. All bytes are initialized to zero and a pointer to the first byte of allocated region is returned. If there is not enough space, a NULL pointer is returned. The following segment of program allocates space to a structure variable.
Text Box: struct student
char name[25];
float age;
long int id_num;
type of struct student record;
record  *stptr;
int class size=30;
stptr = (record *) calloc(class_size, sizeof(record));

record is of type struct student, having three members name, age and id_num. The calloc allocates memory to hold data for 30 such records.


Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More