c - 在 C 中读取文件时出现分段错误
问题描述
我对 c 语言还是很陌生,我第一次玩阅读文件。我有与此代码类似的代码,这些代码过去运行得很好,但现在我遇到了问题。Segmentation fault (core dumped)
每次尝试运行此程序时,我都会不断收到错误消息。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct student {
char first[30];
char last[30];
char ssn[9];
};
void make_arrays() {
FILE *fp = fopen("students.db", "r");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
long num_students = size / sizeof(struct student);
printf("There are %ld students in the file", num_students);
fclose(fp);
}
int main(int argc, char **argv[]) {
make_arrays();
return 0;
}
解决方案
分段错误可能是由于fopen
无法打开文件引起的。
您应该始终测试此类故障并退出并提供信息性消息。
另请注意,如果文件确实是二进制文件,则应以二进制模式打开以避免行尾转换:
FILE *fp = fopen("students.db", "rb");
还将原型更改为main
toint main(int argc, char *argv[])
或简单地int main()
。里面的星星太多了char **argv[]
。
推荐阅读
- java - RxJava 在 Single 异步后执行 Completable
- r - 该行中所有值的总和
- vue.js - 如何在 Vue CLI 3 中配置静态资产文件夹并设置预取?
- python - 如何将表单对象传递给html并在django中使用对象中的每个项目
- c# - 在 WPF 中关闭所有窗口并打开另一个窗口
- r - 创建矩阵时下标越界错误
- amazon-web-services - 将 AWS Appsync 与 AWS Neptune 结合使用
- regex - 将 PCRE 转换为 RabbitMQ/Erlang 正则表达式
- regex - 如何创建与现有正则表达式相反的内容?
- mysql - 基于另一个表 PySpark/SQL 的日期时间列的聚合列