首页 > 解决方案 > 在 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;
}

标签: csegmentation-fault

解决方案


分段错误可能是由于fopen无法打开文件引起的。

您应该始终测试此类故障并退出并提供信息性消息。

另请注意,如果文件确实是二进制文件,则应以二进制模式打开以避免行尾转换:

FILE *fp = fopen("students.db", "rb");

还将原型更改为maintoint main(int argc, char *argv[])或简单地int main()。里面的星星太多了char **argv[]


推荐阅读