从文件中读取十六进制

时间:2017-11-22 20:13:39

标签: c hex stdout

我试图从文件中读取两条记录,其中一条是十六进制格式的数字。好吧,我是C的新手,在我阅读由ftok()生成的十六进制之前,我只使用printf("%x", key)并且它工作正常。现在,当我尝试从文件中读取它时,它不会那样工作。

所以我的代码看起来像这样:

int countRecords(FILE *f_p) {
  int tmp_key = 0;
  int tmp_msgqid = 0;
  int n = 0;

  while (!feof(f_p)) {
    if (fscanf(f_p, "%x %i", &tmp_key, &tmp_msgqid) != 2)
      break;  
    n = n + 1;
  }

  return n;
}

稍后我会在代码中读取此值,如:

printf("Records: %i \n", countRecords(f_msgList));

这个编译没有任何警告。无论如何,当我运行程序时,countRecords(f_msgList)的值为0,当文件中包含大量数据时:

5a0203ff 360448
850203ff 393217
110203ff 425986

编辑: 以下是打开或创建文件的代码:

FILE *f_msgList;
f_msgList = fopen("../message_queues.list", "a");

// if file does not exist then create one and check for errors
if (f_msgList == NULL) {
  FILE *f_tmp;
  f_tmp = fopen("../message_queues.list", "w");
  if (f_msgList == NULL) {
    fprintf(stderr, "Error occurred while creating the file! \n");
    exit(1);
  } else
    f_msgList = f_tmp;
}

1 个答案:

答案 0 :(得分:1)

问题

  • 您以“追加”模式打开文件。这不会让你读完文件。
  • 如果要写入然后读取文件,必须将文件指针重置为文件的开头。
  • feof(f_p)是检查文件指针是否位于文件末尾的最糟糕方式。

解决方案

  • 按“{1}}或”附加+阅读模式'r'以“阅读”模式打开文件。
  • 如果您正在写入文件。写完后用'a+'重置它。
  • 以这种方式阅读文件:

    rewind(f_p);

    这里整数ret是:

    • EOF,如果指针到达文件末尾。
    • 0,如果没有输入与变量匹配
    • (大于0),即带有文件输入的匹配变量数
相关问题