在visual c ++中创建具有越来越多顺序的dat文件

时间:2014-03-24 15:34:29

标签: c++ 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.dat particle1.dat particle2.dat等等;

我如何在visual C ++中实现它;

3 个答案:

答案 0 :(得分:0)

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++;

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果您不仅仅是在格式化字符串时遇到问题,并且希望在多次运行中继续增加文件名,则必须检查已经存在的文件。要做到这一点,你必须使用FindFirstFile和朋友。一个基本的例子:

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