为什么在 C 中使用 bmp 文件时 fopenf_s 将文件指针初始化为 NULL?
why would fopenf_s initialize the file pointer to be NULL when working with bmp file in C?
我正在尝试写入现有的 bmp 文件。
该操作应删除其上的数据,这对我来说很好。
首先我想读取原始 header,然后切换宽度和高度数据,然后 "create" 新文件与新 header。
出于某种原因,我设法在 "rb" 模式下打开和读取文件,但是当我尝试在 "wb" 模式或任何其他写入模式下这样做时,文件指针被初始化为 NULL。
使用 struct BmpHeader 读取效果很好。
更新:
使用后:
err = fopens(...);
我知道错误 = 13。
我该如何解决这个问题?
#define HEADERSIZE 54
int **Matrix = GivenMatrix;
FILE *f;
int row, col,i;
BmpHeader header;
long Newwidth, Newheight;
int pixelBytesInRow, padding;
fopen_s(&f, "plate.bmp", "rb");
fread(&header, HEADERSIZE, 1, f);
fclose(f);
Newheight = header.width;
Newwidth = header.height;
header.width = Newwidth;
header.height = Newheight;
fopen_s(&f, "plate.bmp", "wb");
fwrite(&header, HEADERSIZE, 1, f);
fopen_s() returns a non-zero error code and sets the file handle to null and the global value errno to the appropriate error code when an error occurs. To see what happened, use perror() 打印错误信息:
if (fopen_s(&f, "plate.bmp", "wb") != 0) {
perror("could not open plate.bmp");
// Exit or return.
}
perror()
会将系统错误附加到您自己的消息中,并在其前面加上 :
。
打开文件进行阅读时也这样做。永远不要假设文件操作会成功。在执行任何类型的 I/O.
时,您真的 真的 需要进行错误处理
如果错误是"permission denied",那么这通常意味着文件在别处打开。在您自己的程序中,或通过外部程序(如您用来检查 bmp 文件的图像查看器)关闭它。在 Windows 上,如果文件也在其他地方打开,则无法以写入模式打开文件。
如果您想避免忘记关闭文件的情况,您应该使用 C++ 中的 RAII 工具。它可以说是 C++ 中最重要和最有用的部分。在这种情况下,您可以切换到 C++ 流,或者如果您想继续使用 cstdio
API,然后将您的文件句柄包装在您自己的类型中,当它用完时自动关闭句柄范围(在析构函数中,或者通过使用 unique_ptr
并将自定义删除器设置为 fclose
。)
我正在尝试写入现有的 bmp 文件。 该操作应删除其上的数据,这对我来说很好。 首先我想读取原始 header,然后切换宽度和高度数据,然后 "create" 新文件与新 header。 出于某种原因,我设法在 "rb" 模式下打开和读取文件,但是当我尝试在 "wb" 模式或任何其他写入模式下这样做时,文件指针被初始化为 NULL。
使用 struct BmpHeader 读取效果很好。
更新: 使用后:
err = fopens(...);
我知道错误 = 13。 我该如何解决这个问题?
#define HEADERSIZE 54
int **Matrix = GivenMatrix;
FILE *f;
int row, col,i;
BmpHeader header;
long Newwidth, Newheight;
int pixelBytesInRow, padding;
fopen_s(&f, "plate.bmp", "rb");
fread(&header, HEADERSIZE, 1, f);
fclose(f);
Newheight = header.width;
Newwidth = header.height;
header.width = Newwidth;
header.height = Newheight;
fopen_s(&f, "plate.bmp", "wb");
fwrite(&header, HEADERSIZE, 1, f);
fopen_s() returns a non-zero error code and sets the file handle to null and the global value errno to the appropriate error code when an error occurs. To see what happened, use perror() 打印错误信息:
if (fopen_s(&f, "plate.bmp", "wb") != 0) {
perror("could not open plate.bmp");
// Exit or return.
}
perror()
会将系统错误附加到您自己的消息中,并在其前面加上 :
。
打开文件进行阅读时也这样做。永远不要假设文件操作会成功。在执行任何类型的 I/O.
时,您真的 真的 需要进行错误处理如果错误是"permission denied",那么这通常意味着文件在别处打开。在您自己的程序中,或通过外部程序(如您用来检查 bmp 文件的图像查看器)关闭它。在 Windows 上,如果文件也在其他地方打开,则无法以写入模式打开文件。
如果您想避免忘记关闭文件的情况,您应该使用 C++ 中的 RAII 工具。它可以说是 C++ 中最重要和最有用的部分。在这种情况下,您可以切换到 C++ 流,或者如果您想继续使用 cstdio
API,然后将您的文件句柄包装在您自己的类型中,当它用完时自动关闭句柄范围(在析构函数中,或者通过使用 unique_ptr
并将自定义删除器设置为 fclose
。)