结构如下:
typedef struct info_Novel 
{
string url;
string src;     
string title;   
}InfoNovel;
vector<InfoNovel> Info;
请问如何将Info,写入dat文件及从dat文件中读取出来??

解决方案 »

  1.   

    自己定义格式,然后readstring writestring
      

  2.   

    使用 WriteFile 函数,直接把你的 vector 地址放进去就可以写了。
      

  3.   

    可以加分隔符
    两种分隔符
    一种用来分开struct成员
    一种用来分开vector成员
      

  4.   

    楼主顺便把另一贴的分也给我吧.. 曾经见某贴的传说分还有概率换到书本
    typedef struct _st_dat
    {
    int nx;
    float fy;
    char szBuf[12];
    }ST_DAT;void MyWrite(CString strFile, const vector<ST_DAT> &vDat)
    {
    HANDLE hFile = CreateFile(strFile, FILE_WRITE_DATA, FILE_SHARE_READ,
    NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (INVALID_HANDLE_VALUE == hFile)
    {
    return;
    }
    long lLen = vDat.size();
    DWORD dwWrite = 0;
    BOOL bRet = FALSE;
    // 先定长度
    // 12 是随便写的一个偏移,你可能要根据具体的要求具体写
    bRet = WriteFile(hFile, &lLen, 12, &dwWrite, NULL);
    // 移动文件指针
    SetFilePointer(hFile, 12, NULL, FILE_BEGIN);
    // 再写内容
    bRet = WriteFile(hFile, &vDat, sizeof(vDat) * lLen, &dwWrite, NULL);
    CloseHandle(hFile);
    }
    void MyRead(CString strFile, vector<ST_DAT> &vDat)
    {
    long lLen = 0;
    HANDLE hFile = CreateFile(strFile, FILE_READ_DATA, FILE_SHARE_READ,
    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (INVALID_HANDLE_VALUE == hFile)
    {
    return;
    }
    BOOL bRet = 0;
    DWORD dwRead = 0;
    // 12 是随便写的一个偏移,你可能要根据具体的要求具体写
    bRet = ReadFile(hFile, &lLen, 12, &dwRead, NULL);
    vDat.resize(lLen);
    SetFilePointer(hFile, 12, NULL, FILE_BEGIN);
    bRet = ReadFile(hFile, &vDat, lLen * sizeof(ST_DAT), &dwRead, NULL);
    CloseHandle(hFile);
    }
    void testmydat()
    {
    // TODO: 在此添加控件通知处理程序代码
    // OnOK();
    ST_DAT st;
    st.fy = 1.23f;
    st.nx = 2;
    strcpy(st.szBuf, "abd");
    vector<ST_DAT> vs;
    vs.push_back(st);
    st.fy = 2.34f;
    st.nx = 99;
    strcpy(st.szBuf, "xyz");
    vs.push_back(st); CString strFile = TEXT("c:/mydat.dat");
    MyWrite(strFile, vs);
    vector<ST_DAT> vrtest;
    MyRead(strFile, vrtest);
    }
      

  5.   

    //    12 是随便写的一个偏移,你可能要根据具体的要求具体写
        bRet = WriteFile(hFile, &lLen, 12, &dwWrite, NULL);
    这个偏移量12,是指什么
    不好意思,这个函数没用过,自己查费时间
      

  6.   

    要向文件写内容,你得告诉它占多少字节,然后写/读下一个内容的时候,同样要移动指针到正确的位置.
    查个MSDN一分钟而已,比发贴的时间少多了. 这两个函数随手写的,功能都应该能实现,你可能要自己调试一下。
      

  7.   

    奇怪问题,当我写完马上读,能读出来,但是当我
    重新打开程序读的时候,就会挂掉:MSVCP60D.DLL 越界
    vector<InfoNovel>::iterator itr_Begin=vInfo.begin();
    vector<InfoNovel>::iterator itr_End=vInfo.end();
    vector<InfoNovel>::iterator itr_Iter;
    size_t test=vInfo.size();
    for (itr_Iter=itr_Begin;itr_Iter!=itr_End;++itr_Iter)
    {
    CString strUrl=itr_Iter->url.c_str();//挂在这
    CString strTitle=itr_Iter->title.c_str();
    CString strSrc=itr_Iter->src.c_str();
    }
    这个是怎么回事。
      

  8.   

    不好意思,没有调试过,刚才看了一下确实是不对的。
    把上面代码里面的 ReadFile/WriteFile 的第二个参数由原来的 &vDat 改写成 &vDat[0] 就可以了。我自己测试过是可以的。