rezz
rezz

Reputation: 11

Using fopen() in another function

I'm trying to work with files in C. I wanted to have a function that receives a pointer to FILE, asks the name of the file to read, and initalize it for reading. So, I wrote it like this:

void initFileReading(FILE* fp){
    char dic[40];
    printf("Dictionary file: ");
    scanf("%40[^\n]", dic);

    fp = fopen(dic, "r");
}

int main(){
    int diff, i, nWords, Len;
    char str[16];
    FILE* fp;

    initFileReading(fp);

    fscanf(fp, "%s", str);
    printf("%s", str);

    return 0;
}

When I try to run it I get a SegFault. However if I put what's in the function in main it runs fine. Can anyone give me a little insight in this?

Thank you.

Upvotes: 0

Views: 1046

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318468

Assigning to fp will not modify the variable in the calling function - you only have a pointer to a FILE, not a pointer to a pointer to a FILE. But to modify the pointer in the calling function you need exactly this:

void initFileReading(FILE** fpp){
    char dic[40];
    printf("Dictionary file: ");
    scanf("%39[^\n]", dic);

    *fpp = fopen(dic, "r");
}

int main(){
    int diff, i, nWords, Len;
    char str[16];
    FILE* fp;

    initFileReading(&fp);

    fscanf(fp, "%s", str);
    printf("%s", str);

    return 0;
}

However, it would be cleaner to simply return the newly opened file:

FILE* initFileReading(){
    char dic[40];
    printf("Dictionary file: ");
    scanf("%39[^\n]", dic);

    return fopen(dic, "r");
}

In your main function you can then simply use fp = initFileReading();

Upvotes: 2

Mabus
Mabus

Reputation: 1493

The values passed as arguments to a function are copied to local variables inside the function. So, 'fp' in 'initFileReading' is a local variable, and when you assign the return value of fopen to it you aren't assigning that value to 'fp' in 'main'. If you want to do that, 'initFileReading' must accept a pointer (a memory address) to FILE*. In that case, the memory address value is copied also, but when you modify the memory that it points to, you are modifying 'fp' in main.

The function will be like this:

void initFileReading(FILE** fp){
    char dic[40];
    printf("Dictionary file: ");
    scanf("%40[^\n]", dic);

     *fp = fopen(dic, "r");
}

and you call it

initFileReading(&fp);

where & is the address operator, that returns the address of that variable.

Upvotes: 0

Related Questions