Files and Streams:

 

Stream

A logical interface to a file is known as stream. It is a flow of data. A sequence of characters from an input device to computer is called input stream. A sequence of characters from computer to output device is an output stream. A stream is associated with a file using an open operation. The stream is disassociated from a file using close operation.

There are two types of streams in C++.

Text stream

A text stream is a sequence of characters. A certain character translation may occur in a text stream. For example, a new line may be converted to a carriage return/ line feed pair. It means that there may not be a one to one relationship between the written characters and the characters in external device.

Binary stream

A binary stream is a sequence of bytes. The translation is not performed in binary stream. It exists with a one to one correspondence to the external devices. It means that the number of bytes written or read is the same as the number of bytes on the external device. However, an implementation defined number of bytes may be appended to a binary stream.

 

Types of file access methods

The way in which a file can be accessed is called file access method. It depends on the manner in which data is stored in the files. Different file access methods are as follows:

  1. Sequential access method is used to access in the same sequence in which it is stored in file. This method reads and writes data in a sequence.
  2. Random access method is used to access any data item directly without accessing the preceding data. It is fast as compared to sequential access method.

 

Data file

A data file is a collection of related records. A record contains data about an entity. Data files can be used to save any type of data. Files are stored on secondary storage. The data is stored in files permanently.

Normally, a program inputs data from the user and stores it in variables. The data stored in the variables is temporary. When the program ends, all data stored in variable is also destroyed.

Use of Data Files

A data file can be used to provide input to a program. It can also be used to store the output of a program permanently. If a program gets input from a file instead of keyboard, it will get the same data each time it is executed. There will be far less chance of errors.

 

Text File

A type of file that stores the data as readable and printable characters is called text file. A source program of C++ programming is an example of text file. The user can easily view and read the contents of a text file. It can also be printed to get a hard copy.

 

File pointer

File pointer is pointer that refers to a file on the secondary storage. It is a variable of type FILE. It is used to access and manipulate a data file. A program has to declare a file pointer to use a file. The file pointer is associated with a file after declaration. One file pointer can be associated with only one data file.

SYNTAX

The syntax for declaring a file pointer is as follows:

FILE *MyFile;

The identifier MyFile is a file pointer. FILE is the type of MyFile pointer. The symbol ‘*’ indicates that it is a pointer to a file structure. It contains all information that is required to manage files. It must be included in the program to manipulate files.

 

Opening a file

A file should be opened before it can be processed. A function fopen is used to open a file.

SYNTAX

The syntax is as follows;

File_Pointer = fopen(File_Name, Mode);

File_Pointer is the name of file pointer declared in the program.

File_Name is name of data file to be opened.

Mode indicates the mode in which the file is to be opened.

 

Modes of opening Files

A data file can be opened in the following modes:

Mode Explanation
r The file is opened in read mode. The data can be read only and cannot be written or modified. The file must exist already.
w The file is opened in write mode. The data can be written to the file. The existing data in the file is destroyed.
a The file is opened in the append mode. The new data is written at the end of existing data. The data cannot be read in this mode.
r+ The file is opened in read/write mode. The data can be written and read to a file. The file must already exist.
w+ The file is opened in read/write mode. The data can be written to the file. The existing data in the file is destroyed. The data can also be read.
a+ The file is opened in append mode. The new data is written at the end of existing data. The existing data can also be read.

 

Closing a file

When a file is opened a connection is established between the file and the program. After the file has been processed, the connection should be terminated. When the file is closed, the file pointer is also destroyed in the memory. The data file becomes inaccessible. Closing of a file is optional. If it is not closed, the operating system automatically closes it when the program finishes.

Each opened file occupies memory. It is important to close a file because an opened file occupied memory. Closing of file releases the memory occupied by file.

A file is closed by using fclose statement. This function disconnects the opened file from the program.

SYNTAX:
fclose(File_pointer);

fclose is the function that closes a file. File_Pointer is a file pointer that refers to the file to be closed.

 

Writing data in text files

There are three ways to read and write data in text files.

  1. Data can be written to a file one character at a time. fputc function is used for this purpose. Its syntax is as follows:

 SYNTAX: fputc(char, File_Pointer);

  1. Data can be written to a file string. fputs function is used for this purpose. Its syntax is as follows:

SYNTAX: fputs(string, File_Pointer);

  1. Data can be written to a file as formatted input. fprintf function is used for this purpose. Its syntax is as follows:

SYNTAX: fprintf(File_Pointer, Control_String, Write_List);

 

Writing data character by character

Data can be written to file one character at a time by using fputc function. Its syntax is as follows:

fputc(char, File_Pointer);

EXAMPLE

# include <iostream>

using namespace std;

# include <conio.h>

# include <stdio.h>

void main()

{

FILE *out;

char ch;

out = fopen(“c:\\test.txt”,”w”);

cout<< “enter a character (. to end): “;

ch= getche();

while(ch != ‘.’)

{

fputc(ch, out);

ch = getche();

}

fclose(out);

}

The above program will input characters from the keyboard until the user types a dot. The input will be stored in test.txt file on C: drive.

 

Writing data as string in text file

Data is written to file as string by using fputs function. Its syntax is as follows:

fputs(string, File_Pointer);

string is the string to be stored in the file.

File_Pointer is a file pointer associated with a data file in which the string will be written.

EXAMPLE

# include <iostream>

using namespace std;

# include <conio.h>

# include <stdio.h>
void main()

{

FILE *out;

char ch[25];

int i;

if((out = fopen (“c:\\stest.txt”, “w”)) ==NULL)

      cout<<(“File opening error”);

for (i=0;i<3;i++)

{

cout<<”enter string”;

gets(ch);

fputs(ch, out);

fputs(“\n”, out);

}

fclose(out);

getch();

}

 

Reading data character by character in text file

Data can be read from text file one character at a time by using fgetc function. Its syntax is as follows:

ch = fgetc(File_Pointer);

File_Pointer is the file pointer that refers to a file.

fgetc is the function to read the file character by character.

ch is a variable that store the character that is read from the file.

EXAMPLE

# include <iostream>

using namespace std;

# include <conio.h>

# include <stdio.h>
void main()

{

FILE *in;

char ch;

if((in = fopen (“c:\\test.txt”, “r”))==NULL)

       cout<<”File opening error”;

while ((ch = fgetc(in)) != EOF)

        cout<<ch;

fclose(in);

}

The above program reads a file test.txt character by character. The fgetc function continues to read and display the file character by character until it finds EOF character.

The EOF stands for end of file is a special character. It is used t indicate the end of a text file. It is placed after the last character in one file. It is added automatically at the end of files. A constant EOF represents end of file character. EOF is frequently used to find the end of file.

 

Reading data as string from text file

Data can be read from file as string by using fgets function. Its syntax is as follows:

fgets(string, File_Pointer);

string is the string to be stored in the file.

File_Pointer is a file pointer associated with a data file in which the string will be written.

 

Formatted File input and output

The data in formatted output is written in a particular manner with the help of format specifiers. In this method, a series of different types of data is written in files. The data in formatted input is read in particular manner with the help of format specifiers. In this method, dta is read in the same sequence in which it was written.

C++ provides different functions for formatted input and output. These functions are used to read and write data in a specific format. Two most important functions are as follows:

  1. fprintf is used to write formatted output in a file.

SYNTAX

fprintf(File_Pointer, Control_String, Write_list);

Control string contains format specifiers and escape sequences. It indicates the format according to which data is written to data file.

Write_List is a list of variables, constants or expressions whose values are written in the file. Each item in the list is separated by comma.

  1. fscanf is used to read formatted data from a file.

SYNTAX

fscanf(FILE_Pointer, Control_string, Read_list);

Control string contains format specifiers and escape sequences. It indicates the format according to which data is read from data file.

Write_List is a list of variables in which values are stored from the file. Each item in the list is separated by comma.