user1895783
user1895783

Reputation: 381

segmentation fault while reading from a file

I have a problem with the following code:

#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;
}

and here's 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;
}

my ISBNPrefix.h

FILE* open (const char filename[]);

And the content of swagger.txt is: 123456789

When I try to run it to test if it copies the 123456789 into my variable i get a segmentation fault!

Upvotes: 0

Views: 1203

Answers (2)

LihO
LihO

Reputation: 42085

You have problem in your function for opening a file:

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

it should be file = fopen(filename, "r");

Also you designed open function to return NULL if there is no file, but then you don't check its return value once you call it:

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

Also note that fopen and fscanf are C-style functions. Since you are using C++, there are other more convenient means how to read data from a file. Have a look at std::ifstream. Also when you work with C headers in C++, you should include their C++ wrappers: cstdio, cstdlib, etc.

Upvotes: 3

Ed Heal
Ed Heal

Reputation: 59987

You need fopen for a start. Where does ISBNPrefix.cpp come into the picture?

Upvotes: 0

Related Questions