Topic : Simple File I/O Using C++
Author : John Peregrine
Page : << Previous 2  
Go to page :


the next character in the file, but not actually take it. So if you used peek() to look at the next character, using get() right after peek() will give you the same character, and then move the file counter.

The method putback(char) will actually put characters, one at a time, into the stream. I havenít found a use for this one yet, but itís there.

Writing files
Thereís only one extra method here that may concern you. Thatís put(char), which just writes one character at a time to the out stream.

Opening files
When we opened binary files using this syntax:


ofstream fout("file.dat", ios::binary);


The "ios::binary" was an extra flag to give you some options on how to open the file. By default, the file is opened as ASCII, will create the file if it doesnít exist, and it will overwrite the file if it does exist. Here are some more flags you can use to change things up.

ios::app Append to the end of a file
ios::ate Places the file marker at the end of the file, instead of at the beginning
ios::trunc Default. This will truncate an existing file and overwrite it.
ios::nocreate If the file does not exist, it will not create it for you.
ios::noreplace    If the file does already exist, the open will fail.

File status
The only method I have ever used for the file status is eof(), which will return true if the file marker is at the end of the file. The major use I have had with this is within loops. For an example, this code snippet will count the number of occurrences of the lower case Ďeí in the file.


ifstream fin("file.txt");
char ch;
int counter;

while (!fin.eof())
{
   ch = fin.get();
   if (ch == Ďeí)
      counter++;
}

fin.close();



Iíve never used any other methods than those described here. There are many others, but they are rarely used. Consult a C++ book or the help files on file streams for these extra methods.

Conclusion
You should now have a firm grasp on how to do both input and output with ASCII and binary files. There are many methods that you may use to help with your input and output, though not many of them are used. I hope this article helped at least some of you, since I noticed a lot of people didnít know how to use file I/O. Everyone should know. There are obviously other ways to do file I/O, such as with the include file <stdio.h>. I just prefer to use the stream methods because I find them so much cleaner. Good luck to all of you who have read this, and maybe Iíll write for you all again sometime.

John Peregrine, ColdfireV
jperegrine@customcall.com


Page : << Previous 2