// открыть файл для ввода
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():
#include
const int fileCnt = 5;
string fileTabl[ fileCnt ] = {
"Melville", "Joyce", "Musil", "Proust", "Kafka"
};
int main()
{
ifstream inFile; // не связан ни с каким файлом
for ( int ix = 0; ix
бъект класса fstream (производного от iostream) может открывать файл для ввода или вывода. В следующем примере файл word.out сначала считывается, а затем записывается с помощью объекта типа fstream. Созданный ранее в этом разделе файл word.out содержит объект WordCount:
#include fstream
#include "WordCount.h"
int main()
{
WordCount wd;
fstream file;
file.open( "word.out", ios::in );
file wd;
file.close();
cout "Прочитано: " wd endl;