You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中打印缓冲区内容?CS50 Pset4技术求助

解决CS50 PS4中打印512字节块内容的问题

嘿,作为刚上手CS50的新手,碰到这个问题太正常了!我来帮你搞定怎么打印那些512字节的数据块,顺便说说为啥你之前用fwrite没输出~

首先得搞清楚你是想把块内容输出到文件保存,还是直接在终端(控制台)里查看。两种情况的处理方式不一样,我分别给你拆解:

1. 把块内容写入文件保存(用fwrite)

你之前用fwrite没输出,大概率是这几个原因:

  • 没正确打开输出文件(比如没加"wb"二进制模式)
  • 没检查fwrite的返回值,不知道是不是真的写入成功了
  • 读取的缓冲区本身没读到有效数据(比如fread失败了)

给你个完整的示例代码,把每个512字节块写入单独的文件:

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

int main(void) {
    // 打开存储卡原始文件,必须用"rb"二进制模式
    FILE *infile = fopen("card.raw", "rb");
    if (infile == NULL) {
        fprintf(stderr, "Error opening card.raw!\n");
        return 1;
    }

    unsigned char buf[512];
    size_t bytes_read;
    int block_num = 0;

    // 循环读取每个512字节块
    while ((bytes_read = fread(buf, sizeof(unsigned char), 512, infile)) == 512) {
        // 给每个块生成唯一文件名,比如block_001.bin
        char out_filename[20];
        sprintf(out_filename, "block_%03d.bin", block_num);
        
        // 打开输出文件,一定要用"wb"二进制模式!
        FILE *outfile = fopen(out_filename, "wb");
        if (outfile == NULL) {
            fprintf(stderr, "Error opening %s!\n", out_filename);
            fclose(infile);
            return 1;
        }

        // 写入数据块,检查返回值确认写入成功
        size_t written = fwrite(buf, sizeof(unsigned char), 512, outfile);
        if (written != 512) {
            fprintf(stderr, "Only wrote %zu bytes to %s!\n", written, out_filename);
        }

        fclose(outfile);
        block_num++;
    }

    fclose(infile);
    return 0;
}

2. 在终端打印块内容(用十六进制更清晰)

如果想直接在控制台看块内容,千万别直接打印二进制数据——JPEG的二进制里有很多控制字符(比如0x00),终端会把它们当成特殊指令,要么乱码要么直接截断输出。最好的方式是用十六进制格式打印每个字节:

#include <stdio.h>

// 专门的打印函数,把缓冲区内容以十六进制输出
void print_block_hex(unsigned char buf[], size_t size) {
    for (int i = 0; i < size; i++) {
        // %02x 表示用两位十六进制打印,不足补0
        printf("%02x ", buf[i]);
        // 每16个字节换行,方便阅读
        if ((i + 1) % 16 == 0) {
            printf("\n");
        }
    }
    printf("\n");
}

int main(void) {
    FILE *infile = fopen("card.raw", "rb");
    if (infile == NULL) {
        fprintf(stderr, "Error opening card.raw!\n");
        return 1;
    }

    unsigned char buf[512];
    size_t bytes_read;

    while ((bytes_read = fread(buf, sizeof(unsigned char), 512, infile)) == 512) {
        printf("=== Block %d Start ===\n", block_num);
        print_block_hex(buf, 512);
        printf("=== Block %d End ===\n\n", block_num);
        block_num++;
    }

    fclose(infile);
    return 0;
}

关键提醒

  • 不管是读还是写,一定要用二进制模式("rb"读,"wb"写),否则系统会自动转换换行符,破坏二进制数据结构。
  • 每次调用fread和fwrite后,都要检查返回值,确认操作成功——这是排查问题的核心!比如fread返回的是实际读到的字节数,要是不等于512,要么是到文件末尾了,要么读取出错了。

这样调整后,你就能看到每个512字节块的内容啦,也能继续推进JPEG恢复的作业~

内容的提问来源于stack exchange,提问作者doctopus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:10:12