无法读取jpeg二进制数据,缓冲区仅包含4个字节的数据 [英] Cannot read jpeg binary data, buffer only has 4 bytes of data
问题描述
我正在尝试读取JPEG文件并将其存储在C中的缓冲区中,作为HTTP POST请求的标头的一部分,然后使用HTTP POST上载到服务器.但是似乎它只读取图像数据的前4个字节,因为在服务器端,我只得到图像的前4个十六进制字符.我的代码有什么问题?操作系统是LINUX.
I am trying to read the JPEG file and store it in a buffer in C as part of the header of HTTP POST request, then use HTTP POST to upload to the server. But seems that it only reads the first 4 bytes of image data because on the server side I only get the first 4 hex characters of the image. What is wrong with my code? The OS is LINUX.
我意识到在IMAGE的第五个十六进制上,它的0x00,我认为C会将其解释为终止符,或者只是认为文件就此停止...如何避免此问题?
I realize that on the fifth HEX of the IMAGE, its 0x00, which i think C interprets it as the terminator, or it just thinks the file stops right here... How to avoid this issue?
unsigned long fileLen;
char *buffer;
if ((fp = fopen(filename, "rb")) == NULL){
printf("File could not be opened\n");
exit(1);
}else{
fseek(fp, 0, SEEK_END);
fileLen=ftell(fp);
fseek(fp, 0, SEEK_SET);
buffer=(char *)malloc(fileLen);
fread(buffer, fileLen, 1, fp);
fclose(fp);
}
推荐答案
buffer
是char *
,指向char的指针,因此您获得了计算机上指针的大小(4字节,您正在运行32位,对吧?)
buffer
is a char *
, pointer to a char, so you get the size of a pointer on your machine (4 bytes, you are running on 32-bit, right?).
fread
的返回值是读取的字节数,我建议您使用它.
The return value from fread
is the number of bytes read, I suggest you use that.
0x00
只是C中字符串的定界符,在这种情况下不相关.
0x00
is only a delimiter in C for strings, it is not relevant in this case.
顺便说一句,您可能希望考虑引入一些错误处理.如果ftell
失败,它将返回-1,然后在malloc
中使用它.然后,这将失败并返回NULL,您将在fread
中将其用作第一个参数.这将使您违反SIGSEGV细分,即使程序崩溃.
By the way, you might wish to consider putting-in some error handling. If ftell
failed it would return -1, which you then use in your malloc
. This would then fail and return NULL, which you would use in your fread
as the first argument. That will give you a SIGSEGV Segmentation Violation, i.e. crash your program.
另一个问题可能是文件很大.您尝试获取文件末尾以获取其大小(请考虑使用fstat
),但是如果文件大小超出最大堆大小怎么办?例如2 GB的文件?这将导致malloc
失败并返回NULL.
another issue might be if you have a very large file. You seek to end-of-file to get its size (consider using fstat
instead) but what if the file size exceeds your maximum heap size? For example a 2 gigabyte file? That will cause malloc
to fail and return NULL.
这篇关于无法读取jpeg二进制数据,缓冲区仅包含4个字节的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!