2011-07-26 45 views
0

我已經搜索過該網站,並且我還沒有找到對我的問題的答案。在for循環中使用C的fwrite

我的程序輸出一個圖像,我想保存到一個不同的文件,循環迭代後生成的每個圖像。

我的代碼保存文件是這樣的

FILE *fobjecto; 
if ((fobjecto = fopen ("OSEM.ima", "wb")) != NULL)     
{ 
    printf("Writing reconstructed image file"); 
    fwrite (objecto, sizeof(float), (detectorXDim)*detectorYDim*(NSlices-1), fobjecto);  
    fclose (fobjecto);  
}  
else  
    printf("Reconstructed image file could not be saved"); 

我想一個整型變量添加到輸出文件的名字,我試圖用「+」和玩「」但我不解決這個問題。

在此先感謝

+0

這個數字有多大? – vsz

回答

6

你需要像sprintf一些格式化輸出操作(甚至更好的安全雙snprintf):

char buf[512]; // something big enough to hold the filename 
unsigned int counter; 
FILE * fobjecto; 

for (counter = 0; ; ++counter) 
{ 
    snprintf(buf, 512, "OSEM_%04u.ima", counter); 

    if ((fobjecto = fopen(buf, "wb")) != NULL) { /* ... etc. ... */ } 

    // Filenames are OSEM_0000.ima, OSEM_0001.ima, etc. 
} 
+1

對於不超過20個字符的東西,1000有點大。 –

+0

你剛到那裏:)但你可能想修復'fopen'行... – MByD

+1

好吧OK ... :-) –

5
char file_name[256]; 

sprintf(file_name, "OSEM%4.4d.ima", iteration_count); 

if (NULL!=(fobjecto=fopen(file_name, "wb"))) 
    // ... 
2

構建的文件名,你打開它之前:

char filename[256]; 
//... 
sprintf(filename, "OSEM%08X.ima", someIntegerToAddAsHex); 
if ((fobjecto = fopen (filename, "wb")) != NULL)  
//...