2010-02-17 102 views
16

我有10个文件需要打开才能顺序写入。我可以有一个fstream来做到这一点吗?我是否需要在每个文件之间执行任何特殊操作(flush()除外),或者只需为每个文件调用open(file1, fstream::out | std::ofstream::app),并在写入所有10个文件的末尾时关闭流。我可以重用fstream来打开和写入多个文件吗?

回答

20

您需要先关闭它,因为在已打开的流上调用open失败。 (这意味着failbit标志设置为true)。注意close()冲,所以你不必担心:

std::ofstream file("1"); 
// ... 
file.close(); 
file.clear(); // clear flags 
file.open("2"); 
// ... 

// and so on 

另外请注意,您不需要close()它最后一次;析构函数为你做了这些(因此也是flush()'s)。这可能是一个不错的实用功能:

template <typename Stream> 
void reopen(Stream& pStream, const char * pFile, 
      std::ios_base::openmode pMode = ios_base::out) 
{ 
    pStream.close(); 
    pStream.clear(); 
    pStream.open(pFile, pMode); 
} 

,你会得到:

std::ofstream file("1"); 
// ... 
reopen(file, "2") 
// ... 

// and so on 
+4

最好在调用close()和open()之间插入一个调用'clear()',因为状态标志不会被清除。 有关详细说明,请参阅http://gcc.gnu.org/onlinedocs/libstdc++/faq.html#faq.stream_reopening_fails。 – 2010-02-18 20:49:55

+0

有没有类似的'FILE'变量?我的意思是多重用。 Aspecialy给他们写信。 'fclose()'没有帮助。 – 2013-06-24 01:04:58

2

是的,但你必须用它打开一个文件之前每次关闭fstream的。

然而,这是更好地使用新的局部fstream的对象为每个文件访问采取构造函数和析构函数行为的优势:

struct { 
    const char *filename; 
    void (*operation)(fstream&); 
} filelist[] = { 
    { "file1", callback1 }, 
    { "file2", callback2 }, 
    ... 
    { "file10", callback10 }, 
}; 

for (int i = 0; i < 10; ++i) { 
    fstream f(filelist[i].filename); 
    filelist[i].operation(f); 
} 

在上面的代码示例中,fstream的被刷新,每次关闭通过for循环,因为当对象失去范围时调用析构函数。 fstream通过引用callback function来传递,以便可以在没有讨厌的switch语句的情况下以每个文件为基础处理这些操作。如果每个文件的操作都是相同的,则可以消除该构造。

2

关闭一个流意味着flush(),所以只要你打开下一个你应该没问题的每个流。

相关问题