2013-02-25 94 views
0

对于下面的代码:当前文件如何被覆盖?

fstream file("file.txt", ios::in): 

//some code 
//"file" changes here 

file.close(); 
file.clear(); 
file.open("file.txt", ios::out | ios::trunc); 

如何能在最后三行改变,使当前文件没有关闭,但“重开”一切为空白?

+1

你究竟想要做什么,即你的意思是'所有的东西都是空白'?你的问题听起来像是简单地删除和重新创建它会做你想做的。 – us2012 2013-02-25 04:28:22

+0

@ us2012是的,这就像我想完全重新创建该文件,但如果我不需要显式删除和重新制作文件,这将是一件好事。 – 2013-02-25 04:35:23

回答

2

如果我正确理解问题,您希望清除文件中的所有内容而不关闭它(即通过设置EOF位置将文件大小设置为0)。从我所能找到的解决方案来看,这是最有吸引力的。

另一种选择是使用特定于操作系统的函数来设置文件的结尾,例如Windows上的SetEndOfFile()或POSIX上的truncate()。

如果您只想从文件开头写入,Simon的解决方案就可以工作。如果不使用文件结尾设置,则可能会导致垃圾数据超出您写入的最后位置。

1

可以倒带文件:放回置入指针到文件的开头,这样下次你写的东西的时候,它会覆盖该文件的内容。 为此,您可以使用seekp这样的:

fstream file("file.txt", ios::in | ios::out); // Note that you now need 
               // to open the file for writing 
//some code 
//"something" changes here 

file.seekp(0); // file is now rewinded 

注意,它不会删除任何内容。只有当你覆盖它时要小心。

+0

不会'(ios :: in | ios :: out)&〜ios :: ate'也这样做? – 2013-03-22 13:19:08

0

我猜你想避免将围绕“file.txt的”参数,并试图实现类似

void rewrite(std::ofstream & f) 
{ 
    f.close(); 
    f.clear(); 
    f.open(...); // Reopen the file, but we dont know its filename! 
} 

然而ofstream没有为底层流提供的文件名,并没有提供清除现有数据的方法,所以你有点不幸。 (它确实提供了seekp,它可以让您将写入光标放回到文件的开头,但不会截断现有内容......)

我要么只是将文件名传递给需要它的函数

void rewrite(std::ostream & f, const std::string & filename) 
{ 
    f.close(); 
    f.clear(); 
    f.open(filename.c_str(), ios::out); 
} 

或者将文件流和文件名打包到类中。

class ReopenableStream 
{ 
    public: 
    std::string filename; 
    std::ofstream f; 

    void reopen() 
    { 
     f.close(); 
     f.clear(); 
     f.open(filename.c_str(), ios::out); 
    } 

    ... 
}; 

如果你觉得在热心的你可以做ReopenableStream实际上像一个流,让你可以写reopenable_stream<<foo;而不是reopenable_stream.f<<foo但IMO,似乎有点小题大做。