-1

I need to write separate functions for opening/closing the file and working with it. Was recommended to not use global variables in it.

I have a function where I need to open the file and print what's in it(open_file), a second to work with the data in it(do_stuff_in_file), and a third to only close the file and exit the program(close_file).

When I try to call do_stuff_in_file or close_file the program just crashes.

I know I'm supposed to use pointers, but I just can't get it right and I don't know where's the mistake.

int open_file(FILE **fr) {
    if ((fr = fopen("soldcars.txt", "r")) == NULL) {
    printf("File was not opened\n");
    return 1;
    }
    else {
        char testchar;

        while ((testchar = fgetc(fr)) != EOF) {
            ungetc(testchar, fr);
            //just printing whats in the file
        }
    }   
    return 0;
}
int do_stuff_in_file(FILE **fr, int date) {
    if (fr==NULL) {
        printf("File not open yet\n");
        return 1;
    }
    else{ fseek(fr, 0, SEEK_SET); } //doing stuff
    return 0;
}
int close_file(FILE **fr) {
    if (fr==NULL) { 
        printf("It was not even open yet\n");
        return 1; 
    }
    else{
        if (fclose(fr) == EOF) {
            printf("File was not successfully closed");
            return 1;
        }
        else{
            printf("Adios");
            exit(1);
        }
    }
}
int main() {
    char input;
    int date;
    FILE* fr;
    fr = NULL;

    while ((input = getchar()) != 'c') {
        if (input == 'o') open_file(&fr);
        else if (input == 'd') {
            scanf("%d", &date);
            do_stuff_in_file(&fr, date);
        }
    }

    if (input == 'c') {
        close_file(&fr);
    }

    return 0;
}
mynael
  • 15
  • 4

1 Answers1

2

You need to dereference properly. eg

int open_file(FILE **fr) {
    if ((*fr = fopen("soldcars.txt", "r")) == NULL) {
        perror( "soldcars.txt" );
        return 1;
    }

Note *fr = open instead of fr = open. And, in that function, always use *fr, as in fgetc(*fr) vice fgetc(fr). Similarly in the other functions. Because fr is not a FILE *, but *fr is.

William Pursell
  • 204,365
  • 48
  • 270
  • 300