代码之家  ›  专栏  ›  技术社区  ›  Richard Knop

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

c
  •  13
  • Richard Knop  · 技术社区  · 14 年前

    我想这样做:在一个循环中,第一次迭代将一些内容写入名为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 回复  |  直到 9 年前
        1
  •  16
  •   Jookia    14 年前
    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
    }
    
        2
  •  7
  •   PeteUK    14 年前

    #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;
        }
    }
    
        3
  •  2
  •   Nils Pipenbrinck    14 年前
    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
    }
    
        4
  •  2
  •   AndersK    14 年前

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

        5
  •  1
  •   Josh Wieder    9 年前

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