我正在尝试读取以下格式的二进制文件:
图像数量 [4 字节整数]
width [4-byte int]
height [4-byte int]
灰度数据 [width * height bytes]
(同一类型的更多元素)
这是被调用的第一个函数:
int process_file(const char *filename) {
FILE *input_file = fopen(filename, "r");
//Get number of images
unsigned int number_of_images = read_int_from_file(input_file);
//Allocate memory for all images
struct image *images = malloc(sizeof(struct image) * number_of_images);
read_images(images, number_of_images, input_file)
}
Run Code Online (Sandbox Code Playgroud)
这是image任何想知道的人的结构:
struct image {
unsigned int width;
unsigned int height;
unsigned char *data;
};
Run Code Online (Sandbox Code Playgroud)
这就是它的read_int_from_file作用:
static unsigned int read_int_from_file(FILE *file) {
unsigned char chars[4];
if (fread(&chars, sizeof(char), 4, file) != 4) {
fprintf(stderr, "Couldn't read enough bytes!\n");
return 0;
}
//Calculations follow that return right numbers
return out;
}
Run Code Online (Sandbox Code Playgroud)
这就是剩下的:
static int read_images(struct image *images, unsigned int number_of_images, FILE * file) {
struct image *current_image = images;
int i;
for (i = 0; i < number_of_images; i++) {
read_image(current_image++, file)
}
return EXIT_SUCCESS;
}
static int read_image(struct image *image, FILE *file) {
static long int expected_position = 4;
if (ftell(file) != expected_position) {
fprintf(stderr, "Reading @ %lu when should be @ %lu!",
ftell(file), expected_position);
exit(EXIT_FAILURE);
}
unsigned int width = read_int_from_file(file);
unsigned int height = read_int_from_file(file);
unsigned int size = width * height;
unsigned char *data = malloc(sizeof(char) * size);
if (data) {
if (fread(data, sizeof(char), size, file) != size) {
exit(EXIT_FAILURE);
}
image->width = width;
image->height = height;
image->data = data;
expected_position += 2 * 4 + width * height;
return EXIT_SUCCESS;
} else {
exit(EXIT_FAILURE);
}
}
Run Code Online (Sandbox Code Playgroud)
问题是文件指针有时会在不应该这样做的时候继续前进,即我正在点击ftell(file) != expected_position. 我是在大量成功阅读之后才得到它的,但在结束之前也有一段美好的时光。
有谁知道为什么会这样?我的意思是,即使数字是错误的,这种情况也不应该发生,不是吗?谢谢!
MS-DOS 行尾序列是回车、换行符 ( CR NL, 0x0D, 0x0A),而 Unix 仅使用换行符 (NL或0x0A)。
换线
FILE *input_file = fopen(filename, "r");
Run Code Online (Sandbox Code Playgroud)
到
FILE *input_file = fopen(filename, "rb");
Run Code Online (Sandbox Code Playgroud)
否则,在 POSIX 标准“IEEE Std 1003.1-1988”之前的 Unix 系统上,该fread()函数用于翻译CR NL为, 。NL
在 MS-DOS、Windows 及其衍生产品上,它翻译NL为CR NL.
这些翻译导致您对文件位置的看法与 的ftell()计算不同。