gpt4 book ai didi

c++ - 将数据 append 到 C++ 中的文件,但如果程序重新执行则覆盖

转载 作者:太空宇宙 更新时间:2023-11-04 13:08:52 25 4
gpt4 key购买 nike

我想用这样的函数将数据 append 到文件中:

void Fill( string fileName ){
ofstream outputFile(fileName, ofstream::out | ofstream::app);
outputFile << data1 << " " << data2 << endl;
outputFile.close();
}

如果满足某些条件,此函数将在循环中用于写入不同的文件。但是我想在程序运行时从空文件开始,即不要 append 到旧数据。我怎样才能做到这一点?希望我说清楚了。谢谢!

最佳答案

最简单的解决方案是在某个函数中打开您的程序使用的所有文件而不使用 std::ofstream::app,您在开始时调用一次以截断它们。

void resetFiles()
{
static char * fileNames[] = {
// Fill this with filenames of the files you want to truncate
};

for( int i = 0; i < sizeof( fileNames ) / sizeof( fileNames[ 0 ] ); ++i )
std::ofstream( fileNames[ i ] );
}

int main( int argc, char ** argv )
{
resetFiles();

...
}

编辑:因为您确实指定您正在寻找更优雅的解决方案,所以这就是我想出的。基本上,您声明一个新类,该类继承自 std::ofstream,静态 std::map 成员称为 record。您添加一个允许您指定文件名的构造函数。然后它通过检查记录中是否存在键 fileName 来查找文件是否已经打开一次。如果不是,则使用 std::ofstream::trunc 打开它并将 record[ fileName ] 设置为 true。这样,当文件第二次打开时,它知道它必须用 std::ofstream::app 打开它。

class OutFile : public std::ofstream
{
static std::map< std::string, bool > record;

// Helper function
static std::ios_base::openmode hasBeenOpened( std::string fileName )
{
// Test if the key is present
if( record.find( fileName ) == record.end() )
{
record[ fileName ] = true;
return std::ofstream::trunc;
}
else
{
return std::ofstream::app;
}
}

public:
OutFile( const char * filename )
: std::ofstream( filename, hasBeenOpened( std::string( filename ) ) ) {}
};

// Don't forget to initialize record
map< std::string, bool > OutFile::record;

关于c++ - 将数据 append 到 C++ 中的文件,但如果程序重新执行则覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40873849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com