【问题标题】:fread is not reading other file formatsfread 没有读取其他文件格式
【发布时间】:2016-03-08 01:47:58
【问题描述】:

我还是 C 的新手,但是下面的程序编译得很好,(使用 gcc),它甚至在使用文本文件时也可以工作,但是当我使用其他文件格式时,即png,我什么也得不到。控制台吐出?PNG,仅此而已。我不希望图像打印为图像,显然程序没有这样做,但我希望打印 png 文件中的数据。为什么程序不能正常运行?是因为 fread 拒绝文本以外的任何文件吗?

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

FILE *fp;

int main() {
    char buffer[1000];

    fp=fopen("FILE IN QUESTION HERE", "rb");
    if(fp==NULL) {
        perror("An error occured while opening the file...");
        exit(1);
    }
    fread(buffer, 1000, 1, fp);
    printf("%s\n", buffer);
    fclose(fp);

    return 0;
}

【问题讨论】:

  • 你应该读一本 C 书。 fread 不解释读取的数据。
  • 你的fread()真的不好用吗?你用调试器检查了吗?
  • 我完全打算在某个时候阅读一本 C 书籍,我知道我的问题很愚蠢,但我太兴奋了,无法开始使用 C 进行编码。:)
  • 旁注:请在 META 网站上结帐this discussion...

标签: c fread


【解决方案1】:

printf() 中的%s 用于打印以空字符结尾的字符串,而不是二进制数据,并且 PNG 标头包含一个签名,以防止数据被错误地作为文本传输。

(其实PNG签名中没有0x00printf()停在IHDR块大小包含的0x00处)

使用fwrite()输出二进制数据,或通过putchar()逐一打印字节。

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

int main(void) {
    FILE* fp; /* avoid using gloval variables unless it is necessary */
    char buffer[1000] = {0}; /* initialize to avoid undefined behavior */

    fp=fopen("FILE IN QUESTION HERE", "rb");
    if(fp==NULL) {
        perror("An error occured while opening the file...");
        exit(1);
    }
    fread(buffer, 1000, 1, fp);
    fwrite(buffer, 1000, 1, stdout); /* use fwrite instead of printf */
    fclose(fp);

    return 0;
}

【讨论】:

    【解决方案2】:

    fread 不读取其他文件格式

    代码不检查fread() 的结果。 是确定fread()是否有效的方法。

    char buffer[1000];
    // fread(buffer, 1000, 1, fp);
    size_t sz = fread(buffer, 1000, 1, fp);
    if (sz == 0) puts("Did not read an entire block");
    

    fread() 返回读取的块数。在 OP 的情况下,代码试图读取一个 1000 字节的块。建议阅读 1000 个块,每个块 1 个 char,而不是 1000 个块中的 1 个 char。此外,请避免使用幻数。

    for (;;) {
      size_t sz = fread(buffer, sizeof buffer[0], sizeof buffer, fp);
      if (sz == 0) break;
    
      // Somehow print the buffer.
      print_it(buffer, sz);
    }
    

    printf() 的OP 调用需要一个指向字符串的指针。 C string 是一个字符数组,直到并包括终止空字符。 buffer 可能/可能不包含空字符和空字符后的有用数据。

    // Does not work for OP
    // printf("%s\n", buffer);
    

    .png 文件的数据大多是二进制的,几乎没有文字意义。下面是混合二进制数据和文本的示例打印函数。在学习 .png 文件格式之前,大多数输出​​将显得毫无意义。未经测试的代码。

    int print_it(const unsigned char *x, size_t sz) {
      char buf[5];
      unsigned column = 0;
      while (sz > 0) {
        sz--;
        if (isgraph(*x) && *x != `(`) {
          sprintf(buf, "%c", *x);
        } else {
          sprintf(buf, "(%02X)", *x);
        }
        column += strlen(buf);
        if (column > 80) {
          column = 0;
          fputc('\n', stdout);
        }
        fputs(buf, stdout);
      }
      if (column > 0)  fputc('\n', stdout);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 2011-05-21
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多