【问题标题】:Getting a Seg Fault when reading in Data from a text file in C从 C 中的文本文件中读取数据时出现 Seg 错误
【发布时间】:2020-02-05 22:54:35
【问题描述】:

我正在尝试从文本文件中获取信息并将其读入,在我的主要内容中,我获取文件的长度(以字节为单位)以及文件的名称以确保它存在,并将其传递给这种方法。

我有一些测试代码用于查看问题出在哪里,但我似乎看不到 seg 错误来自哪里,fgetc 返回值与其存储的值匹配,这是我唯一能想到的.

uint32 getCode(char *fileA, int count){
   //creating variables to store the data we are reading in
   int buffer = 0;
   register uint64 total = 0;

   //opening with rb ensures that all file types will be readable
   FILE *file;
   if(file= fopen(fileA, "rb")){
      printf("\nfilename: %s\ncount: %d\n",fileA,count);
   }
   // while loop reading in 32 bits at a time or 4 bytes
   while(count > 0){
      buffer = fgetc(file);
      count--;
      printf("\n%s", buffer);
   }

   fclose(file);
   return 1;
}

【问题讨论】:

  • 打印时使用%c 格式,现在您将int 传递给%s。另外,启用编译器警告。
  • 你也用file,即使打开失败,也可能是空指针。
  • printf("\n%s", buffer); ??缓冲区是一个整数。
  • 真的很想编辑问题的标题并将其更改为:Getting a Seg Fault when calling printf with invalid format string。读取数据与段故障无关。
  • 总是在 Warnings Enabled 的情况下编译。很明显你没有,或者选择忽略它们。对于 gcc/clang,最少使用 -Wall -Wextra -pedantic(也建议使用 -Wshadow),对于 VS 使用 /W3,并且在编译无警告之前不要接受代码。

标签: c file segmentation-fault


【解决方案1】:

分段错误来自printf("\n%s", buffer);——你的buffer不是字符串,使用'%c'格式打印可能会得到更好的结果

是的,// while loop reading in 32 bits at a time or 4 bytes 的评论有点误导,因为您一次读取 1 个字节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-30
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多