C语言中用fread()读取含十六进制的二进制文件输出异常问题
01 Output from Binary Hex File Let’s work through why you’re not seeing the 01 you expect from your binary file, even after using fseek() to jump to the start. Here are the most common issues and fixes to try:
1. You’re Opening the File in Text Mode (Not Binary Mode)
This is the top culprit, especially on Windows. When you use "r" instead of "rb" to open the file, the OS will mangle binary data: it converts newline sequences (e.g., 0x0D 0x0A to 0x0A) and treats 0x1A as an end-of-file marker. Even if your file starts with 01, text mode can alter the data before you read it.
Fix: Always open binary files with the binary read flag:
FILE *fp = fopen("your_file.bin", "rb");
2. Your Reading/Output Formatting Is Off
If you’re using the wrong functions or format specifiers, you’ll miss the 01 you’re looking for:
- Using
%xwithout padding will print1instead of01(use%02xto force two-digit hex output). - Using
charinstead ofunsigned charcan cause sign extension issues (while0x01is safe, this is a critical habit for other hex values). - Text-based functions like
fgets()will treat binary data as a string, stopping at the first null byte.
Correct Reading & Output Example:
unsigned char byte; // Read one byte from the file if (fread(&byte, sizeof(unsigned char), 1, fp) == 1) { // Print with leading zero to get "01" instead of "1" printf("%02x\n", byte); }
If you prefer fgetc():
int c = fgetc(fp); if (c != EOF) { printf("%02x\n", (unsigned char)c); }
3. Did You Check if fseek() Actually Succeeded?
It’s easy to skip error checking. If fseek() fails (e.g., invalid file handle), your file pointer won’t be at the start. Always verify the return value:
if (fseek(fp, 0, SEEK_SET) != 0) { perror("fseek failed"); // Clean up: close file, exit, etc. }
4. Make Sure No Accidental Reads Happened Before fseek()
If you called a read function (like fgetc()) right after opening the file, you’d be reading the second byte instead of the first when you seek back. Double-check that your fseek() is the first operation after opening the file.
Minimal Test Code
Here’s a verified program to test reading the first byte as 01:
#include <stdio.h> #include <stdlib.h> int main() { FILE *fp = fopen("test.bin", "rb"); if (!fp) { perror("Couldn't open file"); return EXIT_FAILURE; } if (fseek(fp, 0, SEEK_SET) != 0) { perror("Failed to seek to start"); fclose(fp); return EXIT_FAILURE; } unsigned char first_byte; if (fread(&first_byte, 1, 1, fp) != 1) { printf("Failed to read byte or file is empty\n"); fclose(fp); return EXIT_FAILURE; } printf("First byte (hex): %02x\n", first_byte); fclose(fp); return EXIT_SUCCESS; }
If this still doesn’t output 01, double-check that your file actually contains 01 at the start—maybe the screenshot was from a different version, or there’s a hidden header you’re missing.
内容的提问来源于stack exchange,提问作者John hopkins

