将数据附加到C 中的文件,但如果将程序重新执行,则覆盖数据

Append data to a file in C++ but overwrite if the program is re-executed

本文关键字:数据 新执行 执行 覆盖 程序 文件 如果      更新时间:2023-10-16

我想将数据附加到这样的函数中的文件:

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

然后,如果满足某些条件,则将此功能用于循环中以写入不同的文件。但是,我想在程序运行时从空文件开始,即不附加到旧数据。我怎样才能做到这一点?希望我能清楚地表明。谢谢!

最简单的解决方案是在没有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继承,并带有static std :: map&lt;std :: string,bool>成员称为记录。您添加一个构造函数,可让您指定文件名。然后,通过检查键文件名是否存在记录,查找文件是否已经打开。如果没有,它将用std :: ofstream :: trenunc打开它,并将记录[文件名]设置为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;

ofstream::trunc打开文件,然后将该文件传递给您的 Fill函数(而不是文件名字符串)以稍后以附加新数据。

这是一个不完整的示例:

void Fill(ofstream& outputFile) {
  outputFile << data1 << " " << data2 << endl;
}
int main() {
  ofstream outputFile(fileName, ofstream::out | ofstream::trunc);
  Fill(outputFile);
  outputFile.close();
}

(这是假设您是在其他地方将其他数据写入文件。如果您仅从Fill函数触摸此文件,那么David的答案只会从Fill中删除ofstream::app

您传递到函数的ofstream::app参数表示您是否已经存在,要附加到文件。默认行为是您要寻找的。删除该部分,

so:

ofstream outputFile(fileName, ofstream::out);