在visual c++中以递增的顺序创建数据文件

creating dat file with increasing number of order in visual c++

本文关键字:顺序 创建 数据 文件 visual c++      更新时间:2023-10-16

我有

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);
}