To read or write data to files in a C++ application, you can use the ifstream and ofstream classes declared in the fstream.h header file. The ifstream class is used for reading from files and the ofstream class is used for writing to files.
Working with files is the same in C++ and Delphi:
Open a file.
Write data to the file.
Close the file.
Before you start writing to a file, you need to include the fstream.h header file and create an instance of the ofstream class (declared in fstream.h):
ofstream myFile;
To start writing to a file, you only need to call the open method and pass at least the file name:
myFile.open("c:\\data.txt");
You have undoubtedly noticed the two backslash characters in the file name. They are necessary because the backslash character in C++ strings indicates an escape sequence. Table 10-2 shows some C++Builder escape sequences. Note that the table also contains the \\ escape sequence, which must be used in file names to produce the necessary backslash character.
Escape Sequence | Description |
---|---|
\a | Bell |
\b | Backspace |
\f | Formfeed |
\n | Newline |
\r | Carriage return |
\t | Tab |
\\ | Backslash |
\' | Apostrophe |
\" | Double quote |
\? | Question mark |
Once the file is opened, the file variable (instance of ofstream) can be used just like the cout object. Write a string to the file using something like this:
for(int i = 1; i <= 10; i++) myFile << "Line " << i << endl;
When you're done writing to the file, call the close() method to close the file:
myFile.close();
To read text from a file you have to do the following:
Create an instance of the ifstream class.
Declare a buffer (a character array) to store the data while reading.
Use the eof() function to determine if you've reached the end of the file.
Use the getline() function to read a line of text and store it into the buffer (the getline function accepts a pointer to the buffer and the buffer's size — getline(char* _Str, int _Count)).
Close the file when you're done.
Listing 10-12 shows how to write text to a file using the ofstream class and how to read text from the same file using the ifstream class.
Listing 10-12: Using ofstream and ifstream classes to read and write text to a file
#include <iostream.h> #include <fstream.h> #include <vcl.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) { const char* path = "c:\\data.txt"; /* write some text to c:\data.txt */ ofstream myFile; myFile.open(path); for(int i = 1; i <= 10; i++) { myFile << "Line " << i << endl; } myFile.close(); /* display c:\data.txt */ ifstream readFile; char buff[256]; readFile.open(path); while(!readFile.eof()) { readFile.getline(buff, sizeof(buff)); cout << buff << endl; } readFile.close(); getch(); return 0; }