当我尝试读取整个文件时,我的缓冲区中只有4个字节(重量超过4B)。但是当我读取.txt文件时,我成功恢复了整个文件内容。
我在fopen man,malloc mand和fread man中搜索过,但我不明白为什么。
char* readFile(char* path)
{
/*VARIABLES*/
FILE *inFile;
long inFileSize;
long readSize;
char *buffer = NULL;
/*OPEN FILES*/
inFile = fopen(path,"rb");
/*ERROR HANDLING : FILES*/
if(!inFile) {
return "";
}
/*GETTING FILE SIZE*/
fseek(inFile, 0, SEEK_END);
inFileSize = ftell(inFile);
rewind(inFile);
printf("The file is %ld bytes long\n",inFileSize);
/*ALLOCATING MEMORY*/
buffer = (char*) malloc(sizeof(char) * (inFileSize + 1) );
/*READ THE CONTENT AND PUT IT IN THE BUFFER*/
readSize = fread(buffer, sizeof(char), inFileSize, inFile);
/*ERROR HANDLING : readed size != to the file size*/
if (inFileSize != readSize)
{
printf("Freeing buffer\n");
free(buffer);
buffer = NULL;
}
/*ADDING THE END STRING CODE*/
buffer[inFileSize] = '\0';
/*CLOSE THE FILE*/
fclose(inFile);
return buffer;
}
另外,当我将图片扩展名从.jpeg更改为.txt时,我仍然只能获得4个字节。
你能帮助我吗?