在c中打开一个二进制文件

发布于 2025-01-09 22:26:33 字数 453 浏览 0 评论 0原文

我正在尝试将一些二进制数据保存在c中的文件(5个8位向量)中。这是我为此编写的代码:

  FILE* flatencies;
  flatencies=fopen("savelatencies.bin", "wb+");
  if(flatencies == NULL){
      perror("\n Error!: ");
  }
  while(1){
  *p_gpio_capture = 0x0 ;
      for(i=0;i<5;i++){
          fwrite(*(latency+i), 8, 1, flatencies);
      }
  }
  fclose(flatencies);

我正在嵌入式系统中执行此脚本。但我从串行终端中的 perror 收到此消息:“Error!: : I/O error”。我不太明白这个错误,也不知道如何解决。如果有人能帮助我,我将不胜感激。

I am trying to save some binary data in a file (5 vectors of 8 bits) in c. This is the code I have made for that:

  FILE* flatencies;
  flatencies=fopen("savelatencies.bin", "wb+");
  if(flatencies == NULL){
      perror("\n Error!: ");
  }
  while(1){
  *p_gpio_capture = 0x0 ;
      for(i=0;i<5;i++){
          fwrite(*(latency+i), 8, 1, flatencies);
      }
  }
  fclose(flatencies);

I am executing this script in an embedded system. But I get this message from perror in the serial terminal: "Error!: : I/O error". I don't understand very well the error and I don't know how to solve it. If anyone could help me, I would be grateful.

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

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

发布评论

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

评论(1

送君千里 2025-01-16 22:26:33

您的代码中存在一些问题:

  1. 即使打开文件失败,您仍在继续写入文件。
if(flatencies == NULL) {
    perror("\n Error!: ");
    // You should return here
}
...
  1. 您似乎没有脱离 while 循环。这将导致你的程序永远循环。你应该考虑在某个时候打破它。 (实际上,这对我来说似乎没什么用,所以我不明白你为什么要写它)。

至于错误,您应该打印 errno 的值并查看特定于平台的文档以了解其实际含义。

There are some issues in your code:

  1. You are continuing to write to the file even if opening it fails.
if(flatencies == NULL) {
    perror("\n Error!: ");
    // You should return here
}
...
  1. You don't seem to break from the while loop. This will cause your program to loop forever. You should consider breaking from it at some point. (Actually, it seems useless to me so I don't see why you wrote it in the first place).

As for the error, you should print the value of errno and see your platform-specific documentation to know what it actually means.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文