【发布时间】: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