简体   繁体   English

C ++:使用随机名称输出文件

[英]C++: file output with a random name

I'm new to C++ so this might be a very naive question. 我是C ++的新手,所以这可能是一个非常幼稚的问题。 I'm trying to output data to a file by calling a function from my main file. 我试图通过从主文件调用函数将数据输出到文件。 I am calling this function multiple times within my main functions and that's why I need to switch on the append mode for writing the files. 我在主函数中多次调用了此函数,这就是为什么我需要打开追加模式来写入文件的原因。 This line of code writes my output file and works fine: 这行代码写了我的输出文件,并且工作正常:

ofstream outFile("result_col2.plt",ios::app);
.
.
outFile.close();

However, I want to make my output file's name random, and I am trying this: 但是,我想使输出文件的名称随机,我正在尝试这样做:

int number = 1; // let's say
ostringstream convert;
convert << number;
string iLevel_str = convert.str();
string fname = "result_col2" + iLevel_str + ".plt";
ofstream outFile(fname.c_str(),ios::app);
.
.
outFile.close();

But when I do this, my data files are becoming double the size after every run. 但是,当我这样做时,每次运行后,我的数据文件的大小就会变成原来的两倍。 Why is it that it doesn't work in the latter case, but works well in my previous case? 为什么在后一种情况下不起作用,但在我的前一种情况下效果很好? Any suggestions? 有什么建议么?

To make it more understandable, the file named "result_col2.plt" remains the same size after every run of the main function. 为了使其更易于理解,每次运行主函数后,名为“ result_col2.plt”的文件将保持相同大小。 Whereas the file named "result_col21.plt" is doubling in size (first run - 85 kb, then 170 kb, and so on.) 而名为“ result_col21.plt”的文件的大小则增加了一倍(首先运行-85 kb,然后170 kb,依此类推。)

除非您更改int number = 1,否则它将不断打开并不断添加result_col21.plt,因此,加倍操作需要进行for循环,每次迭代均需递增该数字

If you need just a random file name you can use std::tmpnam() standard function, but it will generate random file name located in system "temp" directory. 如果只需要随机文件名,则可以使用std::tmpnam()标准函数,但是它将生成位于系统“ temp”目录中的随机文件名。

For details please refer to: http://en.cppreference.com/w/cpp/io/c/tmpnam 有关详细信息,请参阅: http : //en.cppreference.com/w/cpp/io/c/tmpnam

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM