直接上程序:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream ofs("1.txt");
string str = "hello,world!";
int len = str.length();
ofs.write(str.c_str(),len);
ofs.close();
ifstream ifs("1.txt");
ifs.read(const_cast<char*>(str.c_str()),str.length());//利用const_cast去除c_str的const属性
ifs.close();
cout<<str<<endl;
return 0;
}
这里,我们没有使用c风格的字符串,取而代之的是string类型的对象。利用这个类的成员函数length确定其长度。
对于write和read函数,都需要一个c风格的字符串指针,我们可以利用c_str函数来获取。值得注意的是,这个函数获取的字符串是const char*类型,是不能修改内容的,而read函数则必须填写一个可以修改的字符串指针,于是我们使用了强制类型转化const_cast。