当前位置:编程学习 > C/C++ >>

C++中如何将两个连续的string 类型存入到文件中并读取出来?

我定义了一个对象,对象里有两个数据成员都是string类型,现在如何将这两个string类型存入到一个文件中(最好用二进制文件存储),然后把它们从文件中读取出来,再赋值给这个对象的两个string类型数据成员。
追问:假如说我不知道文件里存的string类型长度是多少,那该怎么做?
其他:#include <iostream>
#include <fstream>
#include <atltime.h>
#include <atlstr.h>
#include <fstream>
#include <windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    char temp[256];
    std::ofstream OFile;
    std::ifstream IFile;
    string s="abced";                                          //你的类对象

    string s2="ab23423ddfgdfgd234234234";   //你的类对象

    OFile.open("C:\\test.txt",std::ios::binary);
    if(OFile.is_open())
    {
        OFile.write(s.c_str(),s.length());
        OFile.seekp(s.length(),std::ios::end);
        OFile.write(s2.c_str(),s2.length());
        OFile.close();
    }
    IFile.open("C:\\test.txt",std::ios::binary);
    if(IFile.is_open())
    {
        IFile.read(temp,s.length());
        string t(temp);
        s=t.substr(0,s.length());
        memset(temp,0,256);
        IFile.seekg(s.length()+1,std::ios::cur);
        IFile.read(temp,s2.length());
        string t2(temp);
        s2=t2.substr(0,s2.length());
        IFile.close();
        cout<<s.c_str()<<endl;
        cout<<s2.c_str()<<endl;
    }
    getchar();
    return 0;
} 

如果char[256] 的长度要发生变化
需要改成 char *temp=(char *)malloc(sizeof(char),length)
IFile.open("C:\\test.txt",std::ios::binary);
    if(IFile.is_open())
    {
        char *temp =(char *)malloc(sizeof(char)*(s.length()+1));  
        memset(temp,0,(s.length()+1));
        IFile.read(temp,s.length());
        string t(temp);
        s=t.substr(0,s.length());
        free( temp);
        temp =(char *)malloc(sizeof(char)*(s2.length()+1));  
        memset(temp,0,(s2.length()+1));
        IFile.seekg(s.length()+1,std::ios::cur);
        IFile.read(temp,s2.length());
        string t2(temp);
        s2=t2.substr(0,s2.length());
        IFile.close();
        free (temp);
        cout<<s.c_str()<<endl;
        cout<<s2.c_str()<<endl;
    } 

上一个:为什么在C语言中这个程序运行不了,哪位高手帮帮忙吧!
下一个:我是一个不是特别新的新手,想学好c语言,想学会做软件。

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,