-3

我正在使用 ubuntu 12.04。我一直在为简单的 C++ 学校项目尝试一些 IDE。但是,使用 codelite、anjuta 和 kdevelop 我遇到了一个问题:当我试图读/写文件时,我得到了分段错误:核心转储。

我正在使用一个基本来源:

#include<stdio.h>

FILE*f=fopen("test.in","r");
FILE*g=fopen("test.out","w");

int main () {

    int a,b;
    fscanf(f,"%d %d",&a,&b);
    fprintf(g,"%d\n",a+b);

    fclose(f);
    fclose(g);

    return 0;
}

我不得不说带有标准输入/标准输出的程序运行良好。

4

1 回答 1

2

The most likely problem is that the calls to fopen are not succeeding, perhaps because your program isn't being run from the same directory that contains the files. In that case, the pointers f and g will be null, and you must check for that before passing them to any C library functions.

You also need to check whether fscanf succeeded, otherwise using a and b will result in undefined behaviour (although that will most likely just cause the program to output garbage rather than crash).

You might be better off using std::fstream from the C++ library; but even then, you'll need to check whether the file streams were opened and the input read successfully.

于 2012-09-10T15:41:01.107 回答