繁体   English   中英

如何使用C ++将向量中的数据写入特定位置的文本文件?

[英]how to write a data from vector to a text file at a particular position using c++?

如果我的文本文件看起来是这样。

usrname@gmail.com 3223434324数据1数据2

name@gamil.com 2343454454 data3 data4

我已经使用vector读取了这些值。 我需要在文件第一行的末尾添加一个字符串。 我该怎么办? 我的代码如下:

system("cls");
cout << "\nView proposal\n";
fstream file1;
string ap, aname, aphno;
file1.open("C:\\Users\\Nandhu\\Desktop\\glosys\\joinpolicy.txt",
    ios::in|ios::app);
while(!file1.eof())
{
    while(getline(file1, text))
    {
        istringstream xstream(text);
        vector<string> vcol;
        while(getline(xstream, word, ','))
        {
            vcol.push_back(word);
        }
        vec.push_back(vcol);
    }
    file1.close();
}
for(vector<vector<string> >::iterator itr = vec.begin();
    itr != vec.end(); itr++)
{
    for(vector<string>::iterator itr2 = itr->begin();
        itr2 != itr->end(); itr2++)
    {
        string str;
        str = *itr2;
        cout << str << " ";
    }
    cout << "\n";
}
cout << "\n1.Approve";
cout << "\n2.Reject";
cout << "\nDo you wish to approve?";
cin >> ans;     
if(ans == 'y')
{
    file1.open("C:\\Users\\Nandhu\\Desktop\\glosys\\joinpolicy.txt",
        ios::in|ios::app);
    file1.seekg(0);
    cout << "\nEnter the customer id you wish to approve for:";
    cin >> aname;
    vec.clear();
    if(file1.is_open())
    {
        while(getline(file1, text))
        {
            istringstream xstream(text);
            vector<string> vcol;
            while(getline(xstream, word, ','))
            {
                vcol.push_back(word);
            }
            vec.push_back(vcol);
        }
        file1.close();
    }

    for(vector<vector<string> >::iterator itr = vec.begin();
        itr != vec.end(); itr++)
    {   
        vector<vector<string> > vec;
        vector<string> vcol;

        for(vector<string>::iterator itr2 = itr->begin();
            itr2 != itr->end(); itr2++)
        {
            string str;
            str=*itr2;
            if(str==aname)
            {
                itr + 3;    
                file1.open("C:\\Users\\Nandhu\\Desktop\\glosys\\joinpolicy.txt",
                    ios::out|ios::app);
                vector<string>.insert(itr->end(), "approved");
                file1 << "approved";
                cout << "approved";
                file1.close();
            }   
        }
    }
}       
break;

您不能直接在文件中间插入数据。 您只能重写整个文件或将其附加到最后。

要在中间插入数据,您有几种选择:

1)将文件读入内存缓冲区,根据需要进行转换,然后将文件截断为零长度,然后从缓冲区重写。

2)为1,而不是截断原始文件,而是写入一个新的(临时)文件,然后在原始文件上重命名。

3)确定您需要进行更改的点,将所有内容读取到该位置后再进行内存更改,然后将文件截断为先前确定的大小,然后以追加模式将内存缓冲区写入该文件。

4)内存映射文件,进行所需的更改并将其刷新到文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM