【问题标题】:please help write structure into binary file [closed]请帮助将结构写入二进制文件[关闭]
【发布时间】:2016-03-31 21:14:43
【问题描述】:

我是 C 新手。我正在尝试创建一个 C 程序作为练习的简单票务系统。

我想将结构写入二进制文件然后读取它。但它没有向二进制文件中写入任何内容。

我得到的只是

文件已成功关闭。

文件已成功关闭。

二进制文件(ticket.bin)还是空的。

如果有人可以输入示例来帮助我理解如何将结构写入二进制文件并读取它。

define STATIONNUM 10//Maximun number of station.

define rate1 160

define rate2 190

define rate3 230

struct Ticket{

    int code;//code of the list
    char station[20];//destination name.
    int price;//transportation fee.
};



int main(){

    FILE *fp;
    int c;//for open close judgement return value.
    int i;//use at for loop.
    
    struct Ticket list[STATIONNUM]={
    {1, "NewYork", rate1},
    {2, "London", rate1},
    {3, "Paris", rate1},
    {4, "Tokyo", rate1},
    {5, "HongKong ", rate2},
    {6, "Sydney", rate2},
    {7, "Milan", rate2},
    {8, "Berlin", rate2},
    {9, "Vancouver", rate3},
    {10, "Afghanistan", rate3},
    };

    //open a binary file to write.
    fp = fopen("ticket.bin", "wb");
    if(! fp){
        printf("open file fail");
    }
    
    //write data into binary file.
   if (fwrite(list, sizeof(list[0]), STATIONNUM, fp) != STATIONNUM);

    //close it.
    c = fclose(fp);
    
    //judge if it's closed.
    if(c == -1){
        printf("File close failed.\n");
    }else if(c == 0){
        printf("File successfully closed.\n");
    }

    //open binary file to read.
    fp = fopen("ticket.bin", "rb");
    if(! fp){
        printf("open file fail");
    }
    
    fread(list, sizeof(struct Ticket), STATIONNUM, fp);
    
    //close it.
    c = fclose(fp);
    
    //judge if it's closed.
    if(c == -1){
        printf("File close failed.\n");
    }else if(c == 0){
        printf("File successfully closed.\n");
    }

}

【问题讨论】:

  • 这是C# 还是C++
  • 看起来更像 C (fopen/printf),尽管所有这些都可以在 c++ 中使用。
  • 此外,如果文件打开失败,您可能应该退出程序,而不是仅仅打印出错误消息并继续。
  • 仔细阅读fwrite(3)手册页(并多次阅读)。
  • 您还尝试在以读取二进制模式打开的文件中使用 fprintf()。

标签: c


【解决方案1】:

你的线路

if (fwrite(list, sizeof(list[0]), STATIONNUM, fp) != STATIONNUM);

至少应该是

if (fwrite(list, sizeof(struct Ticket), 
           STATIONNUM, fp) != STATIONNUM)
  { perror("fwrite"); exit(EXIT_FAILURE); };

然后你可以考虑做if (fflush(fp)) perror("fflush");

你显然忘记了

if fread(list, sizeof(struct Ticket), 
           STATIONNUM, fp) != STATIONNUM)
  { perror("fread"); exit(EXIT_FAILURE); };

fp = fopen("ticket.bin", "rb"); 行成功后。

您在测试每个库调用(如 fopenfread)时是正确的,但如果失败,您应该使用 perror 显示错误原因(或使用 strerror(errno))。

你的代码

 fprintf(fp, "%d\t%s\t%d\n", 
         list[i].code, list[i].station, list[i].price);

没有意义。 (你应该测试那个fprintf 的结果是3,否则perror)。您正在为二进制读取打开的fp 句柄中打印文本! 也许你只想在这里printf

顺便说一句,调用 list 一个实际上是数组的变量完全令人困惑......

【讨论】:

  • 感谢您的友好回复。也感谢所有评论。你能解释一下什么是 { perror("fread");退出(EXIT_FAILURE); };我从未见过 perror 也是 EXIT_FAILURE 一个函数吗?再次非常感谢
  • 花点时间阅读一本好的 C 编程书,也许还有一本系统编程书(在 Linux 上可能是 advancedlinuxprogramming.com ...)。我没有太多时间来教你 C 和系统编程。同时编译所有警告和调试信息(例如gcc -Wall -g)并学习使用调试器(例如gdb
  • 谢谢我使用了您提供的代码,但它仍然没有将任何内容写入二进制文件。 ticket.bin 仍然是空的。谢谢你的时间。抱歉编码不好。
  • 现在是时候花几个小时阅读书籍,学习调试(以及如何使用调试器)了。另外,如果您说明您使用的是哪个操作系统、编译器和编译命令,将会很有帮助。
  • window 7 带有 Tera Term 和名为 UnEditor atm 的编译器,我真的很想看看如何成功地将结构写入二进制文件。
【解决方案2】:

我猜问题出在这里:

(1)

  ...
  //open a binary file to write.
      fp = fopen("ticket.bin", "wb");  
                                 |
                                 v
     ///...fopen("ticket.bin", "w" ); /// 
  ...

(2)

  ...
    //write data into binary file.
      if (fwrite(list, sizeof(list[0]), STATIONNUM, fp) != STATIONNUM);
                 |
                 v
    ///...fwrite(&list,...  /// 
  ...

按照这个例子,尝试一步一步地改变你的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STATIONNUM 10 //Maximun number of station.

#define rate1 160
#define rate2 190
#define rate3 230

struct Ticket
{
  int  code;//code of the list
  char station[20];//destination name.
  int  price;//transportation fee.
};

int main()
{ FILE *fp;
  int i; //use at for loop.
  struct Ticket list[STATIONNUM] =
  {
    {  1, "NewYork      ", rate1 },
    {  2, "London       ", rate1 },
    {  3, "Paris        ", rate1 },
    {  4, "Tokyo        ", rate1 },
    {  5, "HongKong     ", rate2 },
    {  6, "Sydney       ", rate2 },
    {  7, "Milan        ", rate2 },
    {  8, "Berlin       ", rate2 },
    {  9, "Vancouver    ", rate3 },
    { 10, "Afghanistan  ", rate3 },
  };

  // open a binary file to write; write it; and close ///
  if (!(fp = fopen("ticket.bin", "w"))) { printf("open file fail"); }
  if (fwrite(&list, sizeof(list[0]), STATIONNUM, fp) != STATIONNUM);
  if ((fclose(fp))==-1) { printf("File close failed.\n"); }

  // 1-st
  // open binary file to read; read; and close it ///
  if (!(fp = fopen("ticket.bin", "r"))) { printf("open file fail"); }
  fread(&list, sizeof(struct Ticket), STATIONNUM, fp);
  if ((fclose(fp))==-1) { printf("File close failed.\n"); }

  // Display initial information
  for (i=0;i<STATIONNUM;i++)
      { printf("%3d %s %d \n", list[i].code, list[i].station, list[i].price); }
  getchar();

  // Change some thing :) ///
  list[0].code = 20;  strcpy(list[0].station, "MOSKOW       "); list[0].price = 200;
  list[1].code = 30;  strcpy(list[1].station, "MINSK        "); list[1].price = 250;
  list[8].code = 60;  strcpy(list[8].station, "ALMATY       "); list[8].price = 330;
  list[9].code = 90;  strcpy(list[9].station, "VLADIVOSTOK  "); list[9].price = 530;

  // open a binary file to write; write it; close the file ///
  if (!(fp = fopen("ticket.bin", "w"))) { printf("open file fail"); }
  if (fwrite(&list, sizeof(list[0]), STATIONNUM, fp) != STATIONNUM);
  if ((fclose(fp))==-1) { printf("File close failed.\n"); }

  // 2-nd
  // open binary file to read; read; and close it ///
  if (!(fp = fopen("ticket.bin", "r"))) { printf("open file fail"); }
  fread(&list, sizeof(struct Ticket), STATIONNUM, fp);
  if ((fclose(fp))==-1) { printf("File close failed.\n"); }

  // Display new information again
  for (i=0;i<STATIONNUM;i++)
      { printf("%3d %s %d \n", list[i].code, list[i].station, list[i].price); }
  getchar();
  return 0;
}

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多