在visual c++中以递增的顺序创建数据文件
creating dat file with increasing number of order in visual c++
我有
particle:: add_particle(int i)
{
ofstream fp1;
fp1.open("output/particle.dat",ios::binary);
fp1.write((char*)this,sizeof(*this));
fp1.close();
}
fp1.close();
}
并循环使用
for(int i=0;i<20;i++)
{
p.add_particle(i);
}
但是在每个循环中,我希望文件名为particle0.datparticle1.datParticle2.dat等;
如何在visual c++中实现;
for( int i = 0; i < 20; ++i ) {
std::stringstream str;
str << "output/particle" << i << ".dat";
fp1.open(str.str().c_str(), ios::binary);
...
}
你可以指定数字格式:
str.width(2);
str.fill('0');
...
见:http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream
sprintf可能对你的情况很有用。
// create a variable for storing the output buffer
// the following should execute in loop
char buffer[200];
int value = 0;
sprintf(buffer, "output/particle%d.dat", value);
value++;
如果您不只是格式化字符串有问题,并且希望在多次运行中保持文件名的递增,那么您必须检查已经存在的文件。要做到这一点,你必须使用FindFirstFile和friends。一个基本的例子:
unsigned int currentFileNumber(const char *dir, const char *start)
{
unsigned int ret = 0;
unsigned int len;
_Bool matched;
WIN32_FIND_DATA fd;
HANDLE hfind;
char best[MAX_PATH] = "";
char pattern[MAX_PATH];
snprintf(pattern, sizeof(pattern), "%s\%s???.dat", dir, start);
hfind = FindFirstFile(pattern, &fd);
if (hfind != INVALID_HANDLE_VALUE) {
len = strlen(fd.cFileName);
matched = isdigit(fd.cFileName[len-7]) && isdigit(fd.cFileName[len-6]) && isdigit(fd.cFileName[len-5]);
do {
len = strlen(fd.cFileName);
if (((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
&& isdigit(fd.cFileName[len-7])
&& isdigit(fd.cFileName[len-6])
&& isdigit(fd.cFileName[len-5])
&& (!matched || (strcmp(best, fd.cFileName) < 0))) {
matched = 1;
strcpy(best, fd.cFileName);
}
} while (FindNextFile(hfind, &fd));
FindClose(hfind);
if (matched) {
ret = (100 * (best[len-7] - '0')) + (10 * (best[len-6] - '0')) + (best[len-5] - '0') + 1;
}
}
return ret;
}
static void currentFileName(const char *dir, char *dest, size_t size)
{
unsigned int n;
n = currentFileNumber(dir, "particle");
snprintf(dest, size, "%s%3.3u.dat", start, n);
}
相关文章:
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 具有包含其他对象的类的对象创建顺序
- 如何创建线程序列以按照启动顺序执行任务?
- 如何创建跟踪以显示存在递归的调用顺序
- 我不知道如何创建一个以数字/字母顺序打印出我的整数或字符串的程序
- 创建按顺序索引的有序映射
- 虚拟基类的创建顺序
- 替换decorator模式以强制执行创建顺序
- 按执行顺序创建Pthread
- 创建顺序类对象
- 在同一优先级队列中创建递增和递减顺序选项
- C++和QML的对象顺序创建QT
- 对象创建和销毁顺序(按C++排列)
- 使用一个数组以相反的顺序创建另一个数组
- 原始数据包创建导致 IP 字段顺序不正确
- 为具有默认值的非顺序参数函数创建启动器
- 如何设置在运行时创建的Windows控件之间移动的顺序
- 我正在创建一个双链接列表,它将按字母顺序排列姓名列表,但我不确定在int main()函数中放入什么
- 从相同的结构体以相反的顺序创建两个优先级队列
- 在visual c++中以递增的顺序创建数据文件