您的位置:首页 > 编程语言 > C语言/C++

C++学习笔记:对文件流的写入和读取

2016-07-12 16:29 447 查看

前言

c++对文件的读取写入,最简单的是利用下面三个类。

名称描述
ofstreamStream class to write on files
ifstreamStream class to read from files
fstreamStream class to both read and write from/to files.

ofstream建立和写入文件

建立一个名为 test.txt 的文档,写入数据的方式多种。

#include<iostream>
#include<fstream>

using namespace std;

int main() {

ofstream ofs("test.txt");
if ( !ofs.is_open() ) {
cout << "failed" << endl;
return 0;
}

ofs << "hello world!" << endl;  //直接写入

int a = 10086;
ofs << a << endl;  //间接写入

string s = "welcome!";
ofs << s.c_str() << "\t" << a << endl;    //不同格式混合写入

string ss = "this is a test for ofstream!\n";
ofs.write(ss.c_str() , ss.length());      //利用write方法

ofs.close();

system("pause");
}


ifstream读取文件

从 test.txt 文档中读取数据,可以使用不同的数据类型来读取,过程都大同小异。

#include<iostream>
#include<fstream>
#include<sstream>

using namespace std;

int main() {

ifstream ifs;
ifs.open("test.txt" , ios::in);
if ( !ifs ) {
cout << "no such file" << endl;
return 0;
}

cout << "\n**********stringbuf**********\n" << endl;
string str;
stringbuf *sb = new stringbuf();
while ( !ifs.eof() ) {
ifs >> sb;
cout << sb;
str.append(sb->str());
}
cout << "\n**********stringbuf to string**********\n" << endl;
cout << str;
cout << "\n**********char**********\n" << endl;
ifs.seekg(0 , ifs.beg); //当前坐标要归零
char cc;
while ( !ifs.eof() ) {
ifs.get(cc);
cout << cc;
}
ifs.close();

system("pause");
}


最后结果



fstream对文件读写操作

fstream可以说是上面两个的综合,不过个人建议,还是用上面两个类,编程的时候便于区分。

#include<iostream>
#include<fstream>

using namespace std;

int main() {

fstream fs("test2.txt" , ios::out); //创建文件
if ( !fs.is_open() ) {
cout << "failed" << endl;
return 0;
}

fs << "test2" << endl; //写入数据
fs.close();

fs.open("test2.txt" , ios::in); //读取文件
if ( !fs.is_open() ) {
cout << "no such file" << endl;
return 0;
}

char c;
while ( !fs.eof() ) {
fs.get(c);
cout << c;
}

fs.close();

system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: