2010-11-20 4 views

답변

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를 사용하여 파일명을 만들 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

(즉, C 용액이지만 태그가 정확하지 않도록) 다른 방식

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

:

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

좋은 해결책, 저와 함께 일했습니다 :) –

1

나는 아래의 방식으로 이것을 수행했다. 다른 예제 들과는 달리, 이것은 실제로 preprocessor includes 옆에 수정없이 의도 한대로 실제로 컴파일되고 작동합니다. 아래의 솔루션은 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은 하나의 이름으로 계산됩니다 (계정을 잊어 버렸던 것이 확실하지 않습니다). 0에서 10 (<11) 사이에 실제로 11 개의 이름이 있음을 알면 빠르게 확인할 수 있습니다. – insaner

+0

알겠습니다. 그 고정. –

관련 문제