Выбрать главу

Прежде чем пытаться прочитать из файла или записать в него, нужно проверить, что файл был успешно открыт:

if ( ! outfile ) { // открыть файл не удалось

cerr "не могу открыть "copy.out" для записи\n";

exit( -1 );

}

Класс ofstream является производным от ostream. Все определенные в ostream операции применимы и к ofstream. Например, инструкции

char ch = ' ';

outFile.put( '1' ).put( ')' ).put( ch );

outFile "1 + 1 = " (1 + 1) endl;

выводят в файл outFile последовательность символов:

1) 1 + 1 = 2

Следующая программа читает из стандартного ввода символы и копирует их в стандартный вывод:

#include fstream

int main()

{

// открыть файл copy.out для вывода

ofstream outFile( "copy.out" );

if ( ! outFile ) {

cerr "Не могу открыть 'copy.out' для вывода\n";

return -1;

}

char ch;

while ( cin.get( ch ) )

outFile.put( ch );

}

К объекту класса ofstream можно применять и определенные пользователем экземпляры оператора вывода. Данная программа вызывает оператор вывода класса WordCount из предыдущего раздела:

#include fstream

#include "WordCount.h"

int main()

{

// открыть файл word.out для вывода

ofstream oFile( "word.out" );

// здесь проверка успешности открытия ...

// создать и вручную заполнить объект WordCount

WordCount artist("Renoir" );

artist.found( 7, 12 ); artist.found( 34, 18 );

// вызывается оператор (ostream&, const WordCount&);

oFile artist;

}

Чтобы открыть файл только для чтения, применяется объект класса ifstream, производного от istream. Следующая программа читает указанный пользователем файл и копирует его содержимое на стандартный вывод:

#include fstream

#include string

int main()

{

cout "filename: ";

string file_name;

cin file_name;

// открыть файл для ввода

ifstream inFile( file_name.c_str() );

if ( !inFile ) {

cerr "не могу открыть входной файл: "

file_name " -- аварийный останов!\n";

return -1;

}

char ch;

while ( inFile.get( ch ))

cout.put( ch );

}

Программа, показанная ниже, читает наш текстовый файл alice_emma, фильтрует его с помощью функции filter_string() (см. раздел 20.2.1, где приведены текст этой функции и содержимое файла), сортирует строки, удаляет дубликаты и записывает результат на стандартный вывод:

#include fstream

#include iterator

#include vector

#include algorithm

template class InputIterator

void filter_string( InputIterator first, InputIterator last,

string filt_elems = string("\",?."))

{

for ( ; first != last; first++ )

{

string::size_type pos = 0;

while (( pos = (*first).find_first_of( filt_elems, pos ))

!= string::npos )

(*first).erase( pos, 1 );

}

}

int main()

{

ifstream infile( "alice_emma" );

istream_iteratorstring ifile( infile );

istream_iteratorstring eos;

vector string text;

copy( ifile, eos, inserter( text, text.begin() ));

string filt_elems( "\",.?;:" );

filter_string( text.begin(), text.end(), filt_elems );

vectorstring::iterator iter;

sort( text.begin(), text.end() );

iter = unique( text.begin(), text.end() );

text.erase( iter, text.end() );

ofstream outfile( "alice_emma_sort" );

iter = text.begin();

for ( int line_cnt = 1; iter != text.end();

++iter, ++line_cnt )

{

outfile *iter " ";

if ( ! ( line_cnt % 8 ))

outfile '\n';

}

outfile endl;

}

После компиляции и запуска программа выводит следующее:

A Alice Daddy Emma Her I Shyly a

alive almost asks at beautiful bird blows but

creature fiery flight flowing hair has he her

him in is it like long looks magical

mean more no red same says she shush

such tell tells the there through time to

untamed wanting when wind

Объекты классов ofstream и ifstream разрешено определять и без указания имени файла. Позже к этому объекту можно присоединить файл с помощью функции-члена open():

ifstream curFile;

// ...

curFile.open( filename.c_str() );

if ( ! curFile ) // открытие успешно?

// ...

Чтобы закрыть файл (отключить от программы), вызываем функцию-член close():