You are on page 1of 9

Data Files

Allow us to store information permanently, and access and alter information whenever necessary Types of data files
Stream-oriented (Standard) data files: Easier to work with
Text file: consisting of consecutive characters Binary file (unformatted data files): organizes data into blocks. These blocks represent more complex data structure, such as arrays and structures

System-oriented data files: closely related to the computers operating system

Opening and closing a data file


First establish a buffer area, where information is temporarily stored while being transferred between the computers memory and the data file
FILE *ptvar;

FILE is a special structure type that establishes the buffer area, ptvar is pointer (stream pointer or stream) that indicates the beginning of the buffer area.

Opening and closing a data file


Data files must be opened before it is created or processed. This associates the file name with buffer area (i.e. with the stream) It also specifies how the data file will be utilized, as
Read-only file Write-only file Read/write file Ptvar=fopen(file-name, file-type);

Opening and closing a data file


File name is a string, that specifies the name (also location) of the file File-type must be one of the following string:
r =read only file w=write only file. Destroy existing same name file a=file for appending. New file created (if no file) r+=both read and write file w+=both read and write file. Destroy existing file. a+=file for reading and appending. New file create

Opening and closing a data file


fopen function returns a pointer to the beginning of the buffer area associated with file. (returns NULL is file does not exist) Data files must be closed at the end of the of the program fclose(ptvar)

Reading and writing a data file


putc(a, fpt): put a character into a data file c=getc(fpt):read a character from a data file fprintf(fpt,%s,custome.name): write the value of a variable into a file fscanf(fpt,%s, customer.name): read a value from a file and store in a variable feof(fpt):check whether end-of-file has been reached or not

Reading and writing unformatted data file


fwrite(&customer, sizeof(record),1,fpt): write a block of data stored in the variable customer, whose data type is record, in the file fpt 1 time fread(&customer, sizeof(record),1,fpt): read a block of data stored in the variable customer, whose data type is record, from the file fpt 1 time

Problems
Take input from keyboard and store in a file Read from a file and display in the monitor Copy a file Encoding and decoding a file Create a file containing customer record Creating an unformatted data file containing customer record

Some more functions related to file


fseek: seek a position and reposition the file pointer of a strean remove: delete a file ftell: return the current file pointer.Used to find the size of a file

You might also like