gpt4 book ai didi

c - 在 C 中显示文件内容 - 写访问错误

转载 作者:行者123 更新时间:2023-11-30 16:20:45 25 4
gpt4 key购买 nike

我正在尝试打印存储在先前函数中的 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 是否正确指向文件的开头?(该文件是四个方形颜色的小十六进制文件)。

最佳答案

unsigned char fileSize = 0;更改为size_t fileSize = 0; (您的位图肯定会大于 255 字节。)然后(2)在void displayBmpFile()中执行size_t n = fileSize; unsigned char *p = fileStart;while (n--) printf("%hhu\t", *p++);

关于c - 在 C 中显示文件内容 - 写访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55193362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com