在 for 循环中使用 C 的 fwrite

发布于 2024-11-26 19:46:14 字数 516 浏览 2 评论 0原文

我搜索了该网站,但没有找到我的问题的答案。

我的程序输出一个图像,我想保存到不同的文件,每个图像在循环迭代后生成。

我保存文件的代码是这样的,

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

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

提前致谢

I have searched the site and I haven't found an answer to my problem.

My program outputs an image, and I want to save to a different file, each image produced after an cycle iteration.

My code to save files is this

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

I want to add one integer variable to the output file's name, I have tried playing with "+" and "," but I could not solve it.

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心作怪 2024-12-03 19:46:15

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

You will need some formatted output operation like sprintf (or even better its safe twin 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.
}
习ぎ惯性依靠 2024-12-03 19:46:15
char file_name[256];

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

if (NULL!=(fobjecto=fopen(file_name, "wb")))
  // ...
char file_name[256];

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

if (NULL!=(fobjecto=fopen(file_name, "wb")))
  // ...
好倦 2024-12-03 19:46:15

在打开文件之前构造文件名:

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

construct the file name before you open it:

char filename[256];
//...
sprintf(filename, "OSEM%08X.ima", someIntegerToAddAsHex);
if ((fobjecto = fopen (filename, "wb")) != NULL)      
//...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文