gpt4 book ai didi

c - fopen() 在现有文件上调用时导致段错误

转载 作者:行者123 更新时间:2023-11-30 20:00:54 26 4
gpt4 key购买 nike

当我尝试在 C 中调用 fopen() 时,仅在调用目录中的文件时出现段错误。我正在开发一个使用指纹传感器的项目,将指纹注册到文件中,然后读取该文件以与运行时读取的指纹进行比较。

这是代码的要点。

FILE * file;
// right_thumb.bin is located in the same directory as the file.
// right_thumb.bin is created using fwrite.
file = fopen("right_thumb.bin", "rb");
// program crashes right at the line above, with the segmentation fault error.
ABS_BIR * readImage;
fread(&readImage, sizeof(ABS_BIR), sizeof(&var), file);
// &var is a pointer to the fingerprint that was written
// ABS_BIR is the fingerprint data type
fclose(file);

奇怪的是,以下内容完美地工作......

File * file;
file = fopen("right_thumb.bin", "w");
fwrite(&var, sizeof(ABS_BIR)/*size of the type the fingerprint is stored in*/
, sizeof(&var)/*8*/, file);
fclose(file);
file = fopen("right_thumb.bin", "rb");
fread(&readImage, sizeof(ABS_BIR), sizeof(&var), file);

奇怪的是,我可以自由打开创建的同一文件,但如果我将该文件更改为由该文件的旧实例创建的不同文件,则会收到错误。

最佳答案

看来你理解起来有困难fread fwrite用法和指针变量,它与您的 fopen 调用关系不大

  • fread不会为你分配缓冲区,你需要分配它
  • 当您将
  • readImage 用作 fread 的参数时,它已经是一个指针(未分配) ,所以它的值可以是任何值,
    此外,您还传递了 &readImage 这意味着您将写入指针的地址。这可能是有效的,但我怀疑这就是你的意图。
  • sizeof 返回作为参数传递的变量的大小,例如在您的情况下:sizeof(&var) 返回 var 地址的大小(在您的系统上显然是 8)

我建议您使用调试器,它可以让您深入了解代码的运行情况。

我的猜测是你应该写以下内容:

File * file;
file = fopen("right_thumb.bin", "w");
fwrite(var, sizeof(ABS_BIR)/*size of the type the fingerprint is stored in*/
, 1/* corrected, only one buffer of ABS_BIR size to write*/, file);
fclose(file);

file = fopen("right_thumb.bin", "rb");
ABS_BIR * readImage=malloc(sizeof(ABS_BIR));
fread(readImage, sizeof(ABS_BIR), 1, file);

请注意,当您正在读取和写入大小为 sizeof(ABS_BIR) 的一个缓冲区时,我将您的 sizeof(&var) 实例更改为 1 > 到/从该文件

关于c - fopen() 在现有文件上调用时导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493230/

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