2010-11-20 12 views
12

Chciałbym zrobić coś takiego: W pętli, pierwsza iteracja napisz trochę treści do pliku o nazwie plik0.txt, drugi plik iteracji1.txt i tak dalej, po prostu zwiększ liczbę.Jak dynamicznie zmieniać nazwę pliku podczas pisania w pętli?

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 
} 

Odpowiedz

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 dla słowa "snprintf" zamiast "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

aby utworzyć pliku pomocą sprintf:

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

(chociaż jest to rozwiązanie C tak, znacznik nie jest poprawna)

7

inny sposób wykonać to w 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

Ładne rozwiązanie, współpracowałem ze mną :) –

1

Dokonałem tego w następujący sposób. Zauważ, że w przeciwieństwie do kilku innych przykładów, to faktycznie będzie się kompilować i działać zgodnie z zamierzeniami bez żadnych modyfikacji, poza zawartymi w preprocesorze. Rozwiązanie poniżej iteruje pięćdziesiąt nazw plików.

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

masz na myśli 51 nazw: 0 i 50 każde liczy się jako jedno imię (nie wiesz, którego konta zapomniałeś). Możesz to zobaczyć szybko, zauważając, że od 0 do 10 (<11) jest w rzeczywistości 11 nazw. – insaner

+0

rozumiem. jest naprawione. –

Powiązane problemy