2013-02-18 63 views
0

我想在std::fstream的文件中附加一些文本。我写了这样的事情在启动时清除文件的内容,然后追加

class foo() { 
    foo() {} 
    void print() { 
     std::fstream fout ("/media/c/tables.txt", std::fstream::app| std::fstream::out); 
     // some fout 
    } 
}; 

问题与这种结构是,每次我运行我的程序时,该文本被追加到我以前的运行。例如,在第一次运行结束时,文件大小为60KB。在第二次运行开始时,文本被附加到60KB文件。

为了解决这个问题,我想在构造函数中初始化fstream,然后以追加模式打开它。像这样

class foo() { 
    std::fstream fout; 
    foo() { 
     fout.open("/media/c/tables.txt", std::fstream::out); 
    } 
    void print() { 
     fout.open("/media/c/tables.txt", std::fstream::app); 
     // some fout 
    } 
}; 

此代码的问题是在执行期间和运行结束时的0大小的文件!

+1

为什么你打开/关闭文件每个打印? – user1278743 2013-02-18 15:50:14

+1

只需打开它而不追加。只要文件没有重新打开,所有后续的写入都将被相继写入。 – hmjd 2013-02-18 15:50:39

+0

我没有关闭该文件。你推荐什么? – mahmood 2013-02-18 15:50:59

回答

3

你只需要打开文件一次:

class foo() { 
    std::fstream fout; 
    foo() { 
     fout.open("/media/c/tables.txt", std::fstream::out); 
    } 
    void print() { 
     //write whatever you want to the file 
    } 
    ~foo(){ 
     fout.close() 
    } 
}; 
+0

太糟糕了,这不是一个有效的C++代码。 – LihO 2013-02-18 16:09:14

0

你的类应该看起来更像是这样的:

#include <fstream> 

class Writer 
{ 
public: 
    Writer(const char* filename) { of_.open(filename); } 
    ~Writer(){ of_.close(); } 
    void print() { 
     // writing... of_ << "something"; etc. 
     of_.flush(); 
    } 
private: 
    std::ofstream of_; 
}; 

注意,文件流此刻Writer对象是一次开放正在构建并在析构函数close()被调用,它也自动写入任何待处理的输出到物理文件。可选地,在每次写入流之后,您可以拨打flush()以确保输出尽快送到您的文件。

这个类的可能用法:

{ 
    Writer w("/media/c/tables.txt"); 
    w.print(); 
} // w goes out of scope here, output stream is closed automatically