c - 尝试读取文件时出现段错误?

标签 c file io segmentation-fault

我传入 argv[1] 作为文件名,但出现段错误,但我不知道为什么。我正在使用一个链表来保存包含 2 个字符和一个 int 的 car 结构的实例。我觉得问题出在我的 fscanf 语句中,但我不确定。

void readFile(List *north, List *east, List *south, List *west, char *fileName) {
    char *file = fileName;
    FILE *fp = fopen(file, "r");

    if(!fp) {
        printf("File could not be opened...");
        return;
    }

    while(!feof(fp)) {
        Car *temp = NULL; //Initialize a blank car
        fscanf(fp, "%s %s %d", &temp->direc, &temp->turn, &temp->time); //scan the direction path and time
        //into the Car Node

        //Add to North List
        if(temp->direc == 'N') {
            insertBack(north, temp);
        }

        //Add to East List
        if(temp->direc == 'E') {
            insertBack(east, temp);
        }

        //Add to South List
        if(temp->direc == 'S') {
            insertBack(south, temp);
        }

        //Add to West List
        if(temp->direc == 'W') {
            insertBack(west, temp);
        }

        else {
            printf("Something went wrong...");
            return;
        }
    }
    fclose(fp);
}

最佳答案

Car *temp = NULL; //Initialize a blank car

您不是在此处初始化“空白”汽车。 temp 变量只是NULL。在执行 fscanf 之前使用 malloc 分配空间:

汽车 *temp = malloc(sizeof(Car));

如果“空白”意味着将分配的空间清零,请使用calloc

关于c - 尝试读取文件时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47362780/

相关文章:

c - 中止陷阱 : 6 in C Program

c - 删除链表中的节点

android - 我想在 Android 项目中读取文件

java - Android 中的 CSV 文件无法写入?

c - 模块函数不返回答案

python - 从内存中读取字节 io.BytesIO 后是否可以删除它们?

c# - 如何在存储到文件和数据库之前更改文件名

java - 搜索/索引大量文件

haskell - 传递字符串以在终端中编辑,并在 Haskell 程序中使用 Enter 键确认

c++ - 好的做法将我的DLL使用的辅助文件放在哪里