![]() |
#2
rjsp2015-03-20 08:41
fout.open("Data.dat",ios::binary|ios::in); 也就算了,但竟然有 sizeof(s)
![]() [color=#0000FF]#include <iostream> #include <string> #include <fstream> using namespace std; int main( void ) { string s; { // 将文件 Rata.txt 第一行读入 s 中 ifstream fin("Rata.txt"); // 内容为 3 1 2 if( !fin ) { cerr << "failed to open Rata.txt\n"; return 1; } if( !getline(fin,s) ) { cerr << "failed to read Rata.txt\n"; return 1; } } cout << s << endl; { // 将 s 内容写入到文件 Data.dat 中 ofstream fout( "Data.dat", ios::binary ); if( !fout ) { cerr << "failed to create Data.dat\n"; return 1; } fout.write( s.c_str(), s.size() ); } string temp; { // 将文件 Data.dat 内容读入到 temp 中 ifstream fin( "Data.dat", ios::binary ); if( !fin ) { cerr << "failed to open Data.dat\n"; return 1; } // 获得文件 Data.dat 长度 size_t len; { fin.seekg( 0, ios::end ); len = fin.tellg(); fin.seekg( 0, ios::beg ); } temp.resize( len ); fin.read( &temp[0], len ); } cout << temp << endl; return 0; } [/color] |
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string s;
ifstream fin("Rata.txt"); // 内容为 3 1 2
ofstream fout;
if(fin.fail())
cout<<"error";
getline(fin,s);
fin.close();
cout<<s<<endl;
fout.open("Data.dat",ios::binary|ios::in);
fout.write((char *)&s,sizeof(s));
fout.close();
string temp;
fin.open("Data.dat",ios::binary);
fin.read((char *)&temp,sizeof(s));
cout<<temp;
return 0;
}
调试时访问内存访问冲突。