2010-11-20 11 views
12

Me gustaría hacer algo como esto: en un ciclo, la primera iteración escribe algo de contenido en un archivo llamado archivo0.txt, segunda iteración archivo1.txt y así sucesivamente, simplemente aumente el número.¿Cómo cambiar dinámicamente el nombre del archivo mientras se escribe en un bucle?

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 
} 

Respuesta

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 for 'snprintf' over' 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

Por lo tanto crear el nombre de archivo usando sprintf:

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

(aunque esto es una solución de C de modo que la etiqueta no es correcta)

7

Una forma diferente de hacer en 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

Buena solución, trabajó conmigo :) –

1

Lo logré de la siguiente manera. Tenga en cuenta que, a diferencia de algunos de los otros ejemplos, esto realmente compilará y funcionará según lo previsto sin ninguna modificación al lado del preprocesador. La siguiente solución itera cincuenta nombres de archivo.

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

te refieres a 51 nombres: 0 y 50 cada uno cuenta como un nombre (no estoy seguro de cuál es el que olvidaste contar). Puede ver esto rápidamente al notar que de 0 a 10 (<11) en realidad hay 11 nombres. – insaner

+0

lo entiendo. está arreglado. –

Cuestiones relacionadas