我正在尝试使用C存储先前功能中存储的文件的全部内容。读取文件大小,并相应地使用动态内存分配来创建相对于文件大小的空间。然后使用指针(fp)指向新分配的空间。然后,将文件的内容读入新空间。 (我认为这是我的错误所在)。
// gloabl variables
unsigned char *fp = 0; //pointer to navigate through the opened file.
unsigned char *fileStart = 0; // pointer to save the start address of the file, in case you need to go back to start of file
unsigned char fileSize = 0; // stores the size of file
/* Use dynamic memory allocation to store the entire contents of the file and let that memory be pointed by 'fp'.
Save the start of file in 'fileStart' so that you use it to go to start of file in other functions.
After opening the file, read the file size and use it for dynamic memory allocation to read entire file. */
void loadFile(const char *filename)
{
FILE *p = fopen(filename, "rb");
if (p == NULL) {
printf("File not created, errno = %d\n", errno);
return 1;
}
fseek(p, 0, SEEK_END); // seek to end of file
fileSize = ftell(p); // get current file pointer
fseek(p, 0, SEEK_SET); // seek back to beginning of file
printf("File loaded. File size = %#x bytes\n", fileSize);
fp = malloc(fileSize + 1);
fread(fp, fileSize, 1, p);
fileStart = &fp;
fclose(p);
}
/*Display file in hex.
Display neatly the content of the file as seen in hex editor.
Even after closing the file with fclose(), we have the contents of the file in memory pointed by 'fp' (or 'fileStart' in loadFile()).
So you don't have to open and read the file again.*/
void displayBmpFile()
{
printf("Hex view of loaded bmp file: \n");
while(!feof(fileStart))
printf("%d\t", fgetc(fileStart));
}
我认识到我的第一个职能是错误。首先,我不确定文件的内容是否正确存储。如果内容存储正确,则fp是否正确指向文件?最后,如果以前的所有操作都正常,fileStart是否正确指向文件的开头? (该文件是四个六边形的小十六进制文件)。
答案 0 :(得分:0)
将unsigned char fileSize = 0;
更改为size_t fileSize = 0;
(您的位图肯定会大于255个字节。)
然后,void displayBmpFile()
中的(2)执行size_t n = fileSize; unsigned char *p = fileStart;
和while (n--) printf("%hhu\t", *p++);