我已经搜索了这个网站,但还没有找到我的问题的答案。
我的程序输出一个图像,我想保存到一个不同的文件,每个图像在循环迭代后产生。
我保存文件的代码是

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");

我想在输出文件名中添加一个整型变量,我试过玩“+”和“,”但我无法解决它。
提前谢谢

最佳答案

您将需要一些格式化的输出操作,如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.
}

关于c - 在for循环中使用C的fwrite,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6833879/

10-11 06:58