在for循环中使用C的fwrite

Ber*_*rdo 0 c loops 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");
Run Code Online (Sandbox Code Playgroud)

我想在输出文件的名称中添加一个整数变量,我试过用"+"和","但我无法解决它.

提前致谢

Ker*_* SB 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.
}
Run Code Online (Sandbox Code Playgroud)


Jer*_*fin 5

char file_name[256];

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

if (NULL!=(fobjecto=fopen(file_name, "wb")))
  // ...
Run Code Online (Sandbox Code Playgroud)