繁体   English   中英

从文件读取时出现分段错误

[英]segmentation fault while reading from a file

我的以下代码有问题:

#include <iostream>
#include <stdio.h>
#include "ISBNPrefix.h"
using namespace std;

int main() {

    FILE* file = NULL;
    int area = 0, i = 0;
    long s;

    file = open("swagger.txt");
    fscanf(file, "%ld", &s);
    cout << s << endl;
}

这是ISBNPrefix.cpp:

#include <iostream>
#include <stdio.h>
#include "ISBNPrefix.h"
using namespace std;

FILE* open(const char filename[]) {

    FILE* file = NULL;
    file = fopen("filename", "r");

    if (file != NULL)
        return file;
    else return NULL;
}

我的ISBNPrefix.h

FILE* open (const char filename[]);

而swagger.txt的内容是: 123456789

当我尝试运行它以测试是否将123456789复制到我的变量中时,出现分段错误!

您打开文件的功能存在问题:

FILE* open(const char filename[]) {
    FILE* file = NULL;
    file = fopen("filename", "r"); <-- here

它应该是file = fopen(filename, "r");

此外,您还设计了open函数,以在没有文件的情况下返回NULL ,但是一旦调用它,便不再检查其返回值:

file = open("swagger.txt");
if (file == NULL) ...        <-- you should check the return value
fscanf(file, "%ld", &s);

还要注意, fopenfscanf是C样式的函数。 由于您使用的是C ++,因此还有其他更便捷的方法来从文件中读取数据。 看看std::ifstream 同样,在C ++中使用C头文件时,还应包括它们的C ++包装器: cstdiocstdlib等。

您需要先打开fopen ISBNPrefix.cpp在哪里出现?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM