如何在C ++中编辑文件 [英] How to edit a file in C++

查看:125
本文介绍了如何在C ++中编辑文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个文件并将程序进度保存在文件中.
由于我的对象大小复杂且动态,因此我无法使用二进制模式.
因此,我试图将数据保存在普通文本文件中,但无法弄清楚如何打开和编辑文件并再次保存.我尝试下面的代码,但不断出错.有人可以帮我吗?

I want to create a file and save program progress in file.
As my object is Complex and Dynamic in size thus i can''t use binary mode.
Thus i tried to save data in normal text file, but can''t figure out how to open and edit the file and save it again. i tried following code but keep getting error. Can any one help me?

#include <fstream>
#include <limits>
#include<iostream>
using namespace std;

std::fstream& GotoLine(std::fstream& file, unsigned int num){
    file.seekg(std::ios::beg);
    for(unsigned int i=0; i < num - 1; ++i){
        file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    }
    return file;
}

std::fstream& GotoLineWrite(std::fstream& file, unsigned int num){
    file.seekg(std::ios::beg);
    for(unsigned int i=0; i < num - 1; ++i){
        file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    }
    long len=0;
    len=file.tellg();
    file.seekp(len,std::ios::beg);
    return file;
}


int main(){
    using namespace std;
    fstream file("bla.txt",ios::in|ios::out);
    GotoLine(file, 4);
    int line=0;
    file >> line;
    cout<<line<<endl;
    line=line+14;
    GotoLineWrite(file,5);
    file<<line;
    cout<<line;
    return 0;
}

推荐答案

文本文件易于创建,但难以修改.
考虑一下:
1.将现有文件加载到对象中.
2.修改对象.
3.将整个对象序列化(保存)为新的临时文件.
4.将新文件复制到旧文件(覆盖文件).

对于相当小的文件,这应该既简单又有效.
如果文件很大(数百兆或更多),请考虑使用某种数据库.

希望这会有所帮助,

Pablo.
Text files are easy to create, but hard to modify.
Consider this:
1. Load the existent file into an object.
2. Modify the object.
3. Serialize (save) the entire object to a new, temporary file.
4. Copy the new file to the old one (overwriting it).

For reasonably small files, this should be both simple and efficient.
If your file is very big (hundreds of megabytes or more), consider using some kind of database.

Hope this helps,

Pablo.


由于我的对象大小复杂且动态,因此我无法使用二进制模式.

这是为什么您应该使用二进制模式的一个很好的理由.您可以将一个对象直接写到文件中,然后直接将其读回到一个对象中,这使得这种过程非常容易实现.
As my object is Complex and Dynamic in size thus i can''t use binary mode.

That is a very good reason why you should use binary mode. You can write an object direct to your file and read it back direct into an object, which makes this sort of process very simple to implement.


这篇关于如何在C ++中编辑文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆