开发者

reading an image file into a char array

开发者 https://www.devze.com 2023-03-01 23:11 出处:网络
I am trying to read a bunch of files into a char array, I have the following code FILE* file = fopen(\"...\",\"rb\");

I am trying to read a bunch of files into a char array, I have the following code

FILE* file = fopen("...","rb");
//some error checking stuff
fseek(file, 0, SEEK_END);
long len=ftell(file);
fseek(file, 0, SEEK_SET);           
char* content=(char *)malloc(len+1);
memset(content,0,len+1);
fread(content, len, 1, file);

I tested this with a text file, and that seems to work. I get the contents of the file in my array and all is good. but if this code runs with an image file (I tested pngs and jpegs), t开发者_开发百科his only seems to read the first few bytes of the file. Is there something I'm missing here?


If you look at the definintion of fread, then it's not possible that your fread returns only the first few bytes since you put len into the size field and pass a count of 1. This means that fread will either return 1 on successfully reading len bytes, or it will fail having read no bytes. If you swap the parameters around then fread will read as many bytes as it can and will return how many bytes it actually read (should be len on success).

Also note that doing a memset 0 and then freading is inefficient, unless you demand that the array is zeroed on failure (error case should mean you don't have to). A better approach to adding the null terminator (as you do for normal files) would be:

content[len] = '\0';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号