如何在循环中写入时动态更改文件名?

时间:2010-11-20 13:02:13

标签: c

我想做这样的事情:在一个循环中,第一次迭代将一些内容写入名为file0.txt的文件,第二次迭代file1.txt等等,只需增加数量。

FILE *img;
int k = 0;
while (true)
{
            // here we get some data into variable data

    file = fopen("file.txt", "wb");
    fwrite (data, 1, strlen(data) , file);
    fclose(file );

    k++;

            // here we check some condition so we can return from the loop
}

5 个答案:

答案 0 :(得分:16)

int k = 0;
while (true)
{
    char buffer[32]; // The filename buffer.
    // Put "file" then k then ".txt" in to filename.
    snprintf(buffer, sizeof(char) * 32, "file%i.txt", k);

    // here we get some data into variable data

    file = fopen(buffer, "wb");
    fwrite (data, 1, strlen(data) , file);
    fclose(file );

    k++;

    // here we check some condition so we can return from the loop
}

答案 1 :(得分:7)

在C ++中使用它的另一种方法:

#include <iostream>
#include <fstream>
#include <sstream>

int main()
{
    std::string someData = "this is some data that'll get written to each file";
    int k = 0;
    while(true)
    {
        // Formulate the filename
        std::ostringstream fn;
        fn << "file" << k << ".txt";

        // Open and write to the file
        std::ofstream out(fn.str().c_str(),std::ios_base::binary);
        out.write(&someData[0],someData.size());

        ++k;
    }
}

答案 2 :(得分:2)

FILE *img;
int k = 0;
while (true)
{
    // here we get some data into variable data
    char filename[64];
    sprintf (filename, "file%d.txt", k);

    file = fopen(filename, "wb");
    fwrite (data, 1, strlen(data) , file);
    fclose(file );
    k++;

            // here we check some condition so we can return from the loop
}

答案 3 :(得分:2)

所以使用sprintf创建文件名:

char filename[16]; 
sprintf( filename, "file%d.txt", k );  
file = fopen( filename, "wb" ); ...

(虽然这是C解决方案,因此标签不正确)

答案 4 :(得分:1)

我以下面的方式完成了这个。请注意,与其他一些示例不同,这实际上将按照预期处理器包含的方式进行编译和正常运行,而不进行任何修改。下面的解决方案迭代了50个文件名。

int main(void)
{
    for (int k = 0; k < 50; k++)
    {
        char title[8];
        sprintf(title, "%d.txt", k);
        FILE* img = fopen(title, "a");
        char* data = "Write this down";
        fwrite (data, 1, strlen(data) , img);
        fclose(img);
    }
}