2010-11-20 10 views
12

私はこのようなことをしたいと思います:ループでは、最初の反復はfile0.txtという名前のファイルに2番目の反復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 
} 

答えて

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「sprintf」での「snprintf」です。 –

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を使用してファイル名を作成する:

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

(タグが正しくないようにC溶液であるが)

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

ニースの解決策は、私と一緒に働いた:) –

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

あなたは51の名前を意味します:0と50はそれぞれ1つの名前としてカウントします。 0から10(<11)には実際に11の名前があることに気付くことで、これをすばやく見ることができます。 – insaner

+0

私はそれを得る。その固定された。 –

関連する問題