Anda di halaman 1dari 6

UNIT-6 FILES

Data files are generally text-based and are used for storing and retrieving related information like
those stored in a database. Managing the information contained in data files is up to the C
programmer. In order to understand how files can be managed, this topic elaborates the
beginning concepts that are used to build files and record layouts for basic data file management.
A File is a collection of related information that is permanently stored on the disk and allows us
to access and alter the information whenever necessary.
Table data File Hierarchy
entity description
bit binary digit, 0 or 1
byte grouping of 8 bits
field grouping of bytes
record grouping of data
file grouping of records
High level files operations:
Naming a File: The file name must be specified for a particular file. The file name is typically a
string of characters. The file names can be data.txt, add.c or program.h so on.
The extension can be given depending upon the usage of the file such as
1. If the file is used for storing text we use .txt extension.
2. If the file stores C program we give .c extension
3. If it is a header file, then we give .h extension so on.
Opening a File: A data file must be opened before it can be created or processed; this associates
the file name with buffer area. Opening a file means, creating a new file with specified filename
and with accessing mode.
Syntax :
FILE *fp;
fp=fopen("filename","mode");
The first statement declares the variable, 'fp' as a pointer to the data type FILE.
The second statement opens the file named filename and assigns identifier to the FILE type
pointer 'fp'. This pointer which contains all the information about the file and it is used as a
communication link between the system and the program.
The mode in the second statement specifies the purpose of accessing the file like read, write etc.
File accessing modes
Mode Purpose
r Used to open the file for reading purpose.
w Used to open the file for writing purpose.
a Used to appending data into the file.
1
r+ Used to open an existing file for reading and writing.
w+ Used to open a new file for both reading and writing.
a+ Used to open an existing file for both reading and writing.

Closing A File: A file must be closed after all the operation of the file has been completed.
Syntax : fclose(file-pointer);
By doing this all the information associated with the file is flushed out from the buffers and all
links to the file are broken. It also prevents any accidental measure of the file.
Example : fclose(fp);
In the above example the statement fclose(fp) is used to close the file, after all operations on
them are completed and used to change the mode of operation. File pointer can be reused for
another file. All files are closed automatically whenever a program terminates.
Creating processing and updating
Creating A Data File: A data file, must be created before it can be processed in two ways. One
is using a text editor or a word processor to create the file directly. The other method is to write a
program that enter information into the computer system and then write it out to the data file.
When creating a new data file with a specially written program, the approach generally used is to
enter the information from the keyboard and then write it out to the data file. If the data file
consists of individual characters, the library functions getchar() and putc() can be used to enter
the data from the keyboard and to write it out to the data file.
Processing A Data File: A data file can be altered as it is being, processed in most of the data
file application. For example, in customer record processing, it may be desirable to add new
records to the file, to delete existing records, to modify the contents of existing records, or to
rearrange the records.
Sequential File: As the name implies that the records are stored and retrieved sequentially i.e.,
one after another. Sequential file is a data structure which consists of a sequence of records of the
same type and size. The records in the file can be read only sequentially. i.e.,One after another
starting from the beginning of the file. The records in the file are arranged in ascending or
descending order of this key field.
Indexed Sequential File: There are many advantages of using an indexed sequential over
sequential. The indexed sequential file maintain two files, they are sequential file and sorted
indexed file. Whatever the data we store it in the sequential file and in the index file we have the
primary key of the sequential file along with the offset of that particular record in the sequential
file.
Random Access File: In case of direct access files, we write the record to a particular position.
Since we are deciding the position of the particular record, there is some relation between the
key (which is used to access the record) using which we are deciding the position of the record.

2
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 following functions.
i) ftell( )
ii) fseek( )
iii) rewind( )
i) ftell( ) : This function is used to specify the current position of a file.
ii) fseek() : It is used to move the file position to a desired location within the file.
iii) rewind() : It is used to takes a file pointer to the starting position of the file and resets the
position to the start of the file.
Example: /* Program using ftell(), fseek() and rewind() functions * /
#include<stdio.h>
main()
{
long int x = 0, m;
FILE * fptr = fopen("vrb.dat", "r");
if (fptr != NULL)
{
fseek(fptr,0L,0); /* fseek() is a function used to position desired point * /
while(x = getc(fptr) != EOF)
putchar(c);
fseek(fptr,0L,2);
x = ftell(fptr); /* ftell() function used to specify the current position * /
printf("\n The size of the file is %d", x);
rewind(fptr);
x = ftell(fptr);
printf("\n The size of the file is %d", x);
}
else
printf("\n The file does not exists");
fclose(fptr); /* file close function closes a file associated with file pointer * /
}
Error Handling: It is possible that an error may occur on a file. Typical error situation are
1. Device over flow.
2. Trying to use a file that has not been opened.
3. Opening a file with an invalid file name.
4. There is enough space on the disc for the file.
5. Attempting to write a write-protected file.

3
The global variable errno is set to a specific value meant to designate the type of error, whenever
an error occurs in a file I/O function. This value can be used to perform the required exception
processing to print the nature of the error the function perror is used. To obtain a char pointer to
the error string the function strerror is used. To reset the error indicator of function clearer is
used.
Example: /* Program to prints the message "Ran out of data" and terminates further reading */
#include<stdio.h>
#include<conio.h>
void main()
{
char *filename;
FILE *fp1,*fp2;
int i,number;
clrscr();
fp1 = fopen("TEST","W");/*file open function creates a new file for r/w operation
for(i = 10;i<=100;i+=10)
putw(i,fp1);
fclose(fp1);
printf("\nInput filename\n");
open_file:
scanf("%s", filename);
if((fp2 = fopen(filename,"r"))==NULL)
{
printf("Cannot open the file.\n");
printf("Type filename again.\n\n");
goto open_file;
}
else
for(i=1;i<=20;i++)
{
number = getw(fp2);
if(feof(fp2))
{
printf("\nRan out of data.\n");
break;
} else
printf("%d\n",number);
}
fclose(fp2); }
Output :
4
Input filename: TESTS
Cannot open the file.
Type filename again.
TEST
10 20 30 40 50 60 70 80 90 100
Ran out of data.

Text and binary files:


The text files are those files that contain letters, digits and symbols. A text file mainly contains
characters coded from the ASCII character set. In C, by default the file stream operations are
performed in text mode but supports binary file operations also.
A binary file is a sequential access file in which data are stored and read back one after another
in the binary format instead of ASCII format.
A binary file is a file that uses all eight bits of a byte for storing information. In contrast to a
binary file, the text uses only seven bits allowing the 8th bit to be 0. So, binary format data file
normally takes less space.
C provides data structure called FILE, declared in file stdio.h, to access the stream of characters
form the disk files. An I/O stream that is active, must have this data type FILE associated with it.
File Pointer: The structure FILE which is declared in stdio.h acts like a link between OS and
the program and it is used to define a file pointer for use in file operations. Therefore, a pointer to
a FILE type is required to work with files on disk.
The Syntax of declaring a file pointer is:
FILE *ptr;
Here fptr is a file pointer of data type FILE. Since C is case sensitive, the word FILE should be
typed in capital letters.
File I/O operations: or Operations on files
After a file is opened, we can read data stored in the file or write new data onto it depending on
the mode of opening. C standard library supports I/O functions.
a) Unformatted file I/O functions:
i). fputc() and fgetc() are character-oriented file I/O functions.
ii). fputs()and fgets() are string oriented file I/O functions.
b) Formatted file I/O functions:
i). fprintf() and fscanf() are mixed data-oriented file I/O functions.
1. Character oriented Functions:
fputs() is to write a character onto a file, the syntax is as-:
fputc(ch, fptr);
where ch represents a character and fptr, a pointer to FILE.
fgetc() is to read a character from a file, the syntax is as follows:
ch= fgetc(fptr);

5
where ch is a variable and fptr, a pointer to FILE.
2. String oriented Functions:
fputs() is to write a string onto a file, the syntax is as-:
fputs(buffer, fptr);
where buffer is the name of a character array and fptr, a pointer to FILE.
fgets() is to reads a string of maximum size-1 characters from the file pointed to by fptr and
copies it to the memory area denoted by buffer.
fgets(buffer,size, fptr);
where buffer is the name of a character array, size is an integer value, fptr is a pointer to FILE
type.
3. Mixed data oriented Functions:
fprintf() is to write multiple data items which may (or not) be of different types to a file. The
syntax is as follows:
fprintf(fptr, control string, arguments-list);
It can be observe that syntax of fprintf() is similar to that of printf() except the presence of an
extra parameter fptr, a pointer to FILE type. The parameter fptr associated with a file that has
been opened for writing. Control string specifies the format specifiers. Argument-list contains
commas separated variables, the values of which are to be written to the file.
fscanf() is to read multiple data items which may be of different types from a file. The syntax is
fscanf (fptr, control string, arguments-list);
It can be observe that syntax of fscanf () is similar to that of scanf () except the presence of an
extra parameter fptr, a pointer to FILE type. The parameter fptr associated with a file that has
been opened for reading. Control string specifies the format specifiers. Argument-list contains
comma separated variables preceded by address of operator & into which data read from the file
are to be copied.
4. Reading and Writing Structures: The main disadvantage of fprintf() is all data types
are treated as characters, for example the data 1234, occupies two bytes in memory but
when it is transferred to the disk file using fprintf() function it would occupy 4 bytes of
memory. For each character one byte would be required.
To overcome this problem the files should be read and write in binary mode, using the
functions fread() and fwrite().
fwrite() function is used for writing a structure block to a given file. The syntax is-
fwrite(&structure_variable, sizeof(structure), integer, file_pointer);
fread() function is used for reading entire structure block to a given file. The syntax is-
fread(&structure_variable, sizeof(structure), integer, file_pointer);

Anda mungkin juga menyukai