注册 登录
编程论坛 C++教室

二进制文件读写

王翔 发布于 2015-03-19 20:53, 410 次点击
#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;
}

调试时访问内存访问冲突。
3 回复
#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]
#3
王翔2015-03-20 10:08
回复 2楼 rjsp
上一个为什么会出错啊  
#4
wp2319572015-03-20 11:06
回复 2楼 rjsp
代码贴里 那些神马ubb标识都不管用了
1