【问题标题】:Problems reading a binary file with fread function使用 fread 函数读取二进制文件时出现问题
【发布时间】:2012-08-22 06:33:19
【问题描述】:

我想要做的是读取“.d”二进制文件的内容并将它们存储在一个数组中。 于是我写了如下代码:

void viewFile()
{
   unsigned char inFileData[SIZE];
   char fileName[SIZE];
   int numRead;

   FILE *inBinFile;


    printf("Enter the file name:");
    scanf("%s", fileName);

    inBinFile = fopen( fileName, "rb");
        if(( inBinFile = fopen(fileName, "rb")) == NULL )
        {
           fprintf( stderr, "Error opening %s\n", fileName );
           clearStdin();/*a function to clear stdin*/
           mainMenu();/*a function to prompt user input*/
        }
    numRead = fread( inFileData, sizeof(unsigned char), SIZE, inBinFile );
    inFileData[SIZE] = '\0';

    printf("U coded data:\n%s\n", inFileData);
    printf("%d\n", numRead);

    fclose(inBinFile);
   return;
}

输出是一堆不可读的垃圾。我做错了哪一部分?没看懂。

另外,我将 clearStdin 函数编写如下:

void clearStdin(void)
{
    scanf("%*[^\n]");
    scanf("%*1[\n]");
   return;
}

编译器没有报告任何错误,但不知何故,函数调用似乎并没有完全按照我想要的方式工作。它确实清除了标准输入,但在调用此函数的任何地方都会出现错误,例如提示用户输入的主菜单函数。

请帮忙!!提前致谢。

【问题讨论】:

  • 除非二进制文件的内容是可读的 ASCII 字符集,否则使用 %s printf() 格式将内容发送到 stdout 通常会导致一堆不可读的垃圾。文件中的实际内容是什么?
  • 你还能期待什么 - 你自己说文件是二进制的,那么为什么它会产生可读的输出?
  • 您打开文件两次是否有原因?
  • Micheal,实际内容只是 0 1 2 3 4 5 6 7 8 9。这就是我感到困惑的地方......谢谢!
  • mathematician1975 设计规范说内容是0 1 2 3 4 5 6 7 8 9,所以想打印出来。。。抱歉没说清楚,谢谢!跨度>

标签: c stdin fread


【解决方案1】:

“输出是一堆不可读的垃圾” - 是的,。这是一个二进制文件,不能作为文本读取。

如果您想以可读形式查看二进制信息,请考虑对其进行十六进制转储。

请参阅here 了解执行此操作的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-30
    • 2019-04-13
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    相关资源
    最近更新 更多