Inside Delphi 2006 (Wordware Delphi Developers Library)

Basic File I/O in C++

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.

Writing Text to a File

Working with files is the same in C++ and Delphi:

  1. Open a file.

  2. Write data to the file.

  3. 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.

Table 10-2: C++ Builder escape sequences

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();

Reading Text from a File

To read text from a file you have to do the following:

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; }

Категории