将数据附加到C 中的文件,但如果将程序重新执行,则覆盖数据
Append data to a file in C++ but overwrite if the program is re-executed
我想将数据附加到这样的函数中的文件:
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);
相关文章:
- 如何在新的派生对象中获取基本对象的数据?
- 如何将图像传入C++可执行文件并将输出图像存储在新目录中?
- C++ TCP 套接字通信 - 连接按预期工作,几秒钟后失败,没有收到新数据,read() 和 recv() 块
- 为什么C++可执行文件在与较新的libstdc++.so链接时运行得更快?
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 编译器如何在编译时执行数据绑定?
- 使用哪种模式来执行新代码,只需添加基类的新子类?
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 将数据复制到磁盘上新位置的语法
- 如何使用 boost::asio 的 async_read_some() 读取所有可用数据,而无需等待新数据到达?
- 是否可以访问类数据成员并在析构函数中对它们执行操作?
- 使用 CMake 在可执行文件中嵌入二进制数据
- 如何在SDL2音频流数据上执行实时FFT
- 对“呍”数据结构执行插入操作
- 如何从数据缓冲区执行 x86 命令
- c++ fstream,从文本中读取数据并执行数学运算
- 如何对模板中的字符串数据类型执行几组不同的指令
- 重用相同的代码对列表中的对象的不同数据成员执行相同的逻辑
- 为什么C++不对指针数据强制执行 const?
- 基于数据集合执行二叉树搜索