Coupon Accepted Successfully!


Sequential Access Files

C++ allows the file manipulation command to access the file sequentially or randomly. The data of the sequential file should be accessed sequentially, that is, one character at a time. In order to access the nth number of bytes, all previous characters are read and ignored. There are a number of functions to perform read and write operations with the files. Some functions read /write single characters, and some functions read/write blocks of binary data. The put() and get() functions are used to read or write a single character, whereas write() and read() are used to read or write blocks of binary data.
put() and get() functions
The function get() is a member function of the class fstream. This function reads a single character from the file pointed by the get pointer, that is, the character at the current get pointer position is caught by the get() function.
The function put() function writes a character to the specified file by the stream object. It is also a member of the fstream class. The put() function places a character in the file indicated by the put pointer.

16.15 Write a program to write and read string to the file using put() and get() functions.




int main()



char text[50];

cout<<“\n Enter a Text:”;


int l=0;

fstream io;

io.open(“data”, ios::in | ios::out);

while (l[text]!=‘\0’)



char c;

cout<<“\n Entered Text:”;

while (io)





return 0;


Explanation: In the above program, the file data is opened simultaneously in the read and write mode. The getline() function reads the string through the keyboard and stores it in the array text [50]. The statement io.put (text[l++]) in the first while loop reads one character from the array and writes it to the file indicated by the stream object io. The first while loop terminates when the null character is found in the text.
The statement io.seekg (0) sets the file pointer at the beginning of the file. In the second while loop, the statement io.get(c) reads one character at a time from the file, and the cout() statement displays the same character on the screen. The while loop terminates when the end of the file is detected.

Test Your Skills Now!
Take a Quiz now
Reviewer Name