2010-11-20 12 views
12

Vorrei fare qualcosa di simile: In un ciclo, prima l'iterazione scrive del contenuto in un file chiamato file0.txt, secondo iterazione file1.txt e così via, basta aumentare il numero.Come cambiare dinamicamente il nome del file mentre si scrive in un ciclo?

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 
} 

risposta

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 per 'snprintf' su' sprintf'. –

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

così creare il nome file utilizzando sprintf:

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

(anche se questo è una soluzione C così l'etichetta non è corretto)

7

Un modo diverso di fare in 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

Bella soluzione, ha funzionato con me :) –

1

Ho compiuto questo nel modo di seguito. Si noti che diversamente da alcuni degli altri esempi, questo verrà compilato e funzionerà come previsto senza alcuna modifica a fianco dei pre-processor. La soluzione sotto itera cinquanta nomi di file.

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

intendi 51 nomi: 0 e 50 ogni conteggio come un nome (non è sicuro quale è quello che hai dimenticato di spiegare). Potete vederlo rapidamente notando che da 0 a 10 (<11) ci sono in realtà 11 nomi. – insaner

+0

ho capito. è sistemato. –

Problemi correlati