【发布时间】:2019-03-28 23:24:17
【问题描述】:
所以我正在尝试读取 C 中的 .bmp 文件。稍后我将使用 openssl 库对该文件进行加密 - 但这只是背景信息。
我需要以二进制模式打开文件(显然),但无论出于何种原因,当我尝试打开文件时,它只读取 4 个字节。当我尝试输出我刚刚打开的这个确切文件(用于错误测试)时,它会输出以下内容 - 88 24 AD FB。
在我的故障排除中,我决定在一个文本文件(54 字节)上尝试这个,我得到了完全相同的结果。
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char * fileName="pic_original.bmp";
//read the file from given filename in binary mode
printf("Start to read the .bmp file \n");
FILE *image;
image = fopen(fileName,"rb");
//print the size of the image (4 bytes every damn time)
printf("Size of image: %d\n",sizeof(image));
//output the exact file that was read (error testing)
FILE *test;
test = fopen("./test.bin", "w");
fwrite(image, sizeof(image), 1, test);
fclose(test);
fclose(image);
return 1;
}
这是图片(出于某种原因上传为 png)
不完全确定我哪里出错了,但我对 C 语言不是很熟悉。
干杯, 利亚姆
编辑 1:
//allocate memory for the header and image
char *headerBuf = (char *)malloc(54);
char *imageBuf = (char *)malloc(sizeof(image)-54); //this line is wrong - thanks to user EOF
//allocate memory for the final ciphertext
char *imagecipherCBC = (char *)malloc(sizeof(image)); //wrong also
//read first 54 bytes (header)
rewind(image);
fread(headerBuf,54,1,image);
//read the bitmap image until the end of the file
fread(imageBuf,sizeof(image),1,image); //also wrong
【问题讨论】:
-
sizeof(image)是sizeof (FILE*)和sizeof(FILE*)不依赖于文件的大小。 -
嗯好吧,那么我将如何输出我读入的确切文件?我是否正确地读取了文件?
-
这取决于。你在哪个平台?您必须专门使用便携式 c,还是可以使用该平台?如果您使用的是 POSIX,
fstatat()是明智的选择,前提是您正在读取文件而不是一般(不可搜索的)流。 -
使用位图文件,首先您可以将标题读入
struct,它会告诉您图像大小。然后,您可以为位图分配内存并读取它。 -
或者,如果您只是复制文件:
size_t bytes; while((bytes = fread(buffer, 1, sizeof buffer, image)) != 0) { fwrite(buffer, 1, bytes, test); }