2010-11-20 64 views
12

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

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

(尽管这是一个C溶液,使该标记是不正确的)

回答

15
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

+1''snprintf' over'sprintf'。 – 2010-11-20 13:12:02

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 
} 
2

使用的sprintf这样创建的文件名它在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; 
    } 
} 
7

一种不同的方式来做到:

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 
} 
+0

不错的解决方案,与我一起工作:) – 2014-02-20 22:16:59

1

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

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

你的意思是51名:0和50每个都算作一个名字(不知道哪一个是你忘记考虑的名字)。你可以很快看到这一点,注意到从0到10(<11)实际上有11个名字。 – insaner 2015-03-28 10:16:11

+0

我明白了。它的固定。 – 2015-07-19 02:50:41