-
1.概念
标准库 fstream定义了3个数据类型如下:
ofstream:该数据类型表示输出文件流,用于创建文件并向文件写入信息。
ifstream:该数据类型表示输入文件流,用于从文件读取信息。
fstream:该数据类型通常表示文件流,且同时具有 ofstream 和 ifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息。 -
2.demo代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void fileTest();
int main ()
{
fileTest();
return 0;
}
/**
* 文件测试
*/
void fileTest(){
string filepath = "D:\\C++Test\\test.txt";
string file_name = "test.txt";
//建立一个读取的ifile,由于读取 input.txt中的内容
cout << file_name.c_str() << endl;
ifstream ifile(filepath.c_str());
if (! ifile)
{
cerr << "oops! unable to open input file: " << file_name << endl;
return;
}
else
{
cerr << "!! ok: opened " << file_name << " for input\n";
}
//新建一个input.txt.sort文件,用于保存排好序的文字
//类型是输出ofile
file_name += ".sort";
ofstream ofile( file_name.c_str() );
if (! ofile)
{
cerr << "oops! unable to open output file: " << file_name << endl;
return;
}
else
{
cerr << "!! ok: opened " << file_name << " for output\n";
}
string word;
vector<string> text;
//读取内容到word至文件末尾
while (ifile >> word)
{
//插入到容器text中
text.push_back( word );
}
if (text.empty())
{
cerr << "bummer! input file is empty: bailing out\n";
return;
}
else
{
cerr << "!! ok: read " << text.size() << " strings from input\n";
}
//排序操作
sort(text.begin(), text.end());
int cnt = 0;
for (vector<string>::iterator iter = text.begin(); iter != text.end(); ++iter )
{
//排列格式
cnt += iter->size() + 1;
if (cnt > 40)
{
ofile << '\n';
cnt = 0;
}
//输出到ofile中,即input.txt.sort文件中
ofile << *iter << ' ';
}
cout << "ok: wrote sorted strings into " << file_name << endl;
}
- 3.控制台输出如下:
D:\C++Test\cmake-build-debug\C__Test.exe
test.txt
ok: wrote sorted strings into test.txt.sort
!! ok: opened test.txt for input
!! ok: opened test.txt.sort for output
!! ok: read 5 strings from input
Process finished with exit code 0