Home > other >  Check if the file was opened in C
Check if the file was opened in C

Time:03-12

I am trying to write a function to check if the file has been opened and if not, open it. The file is defined in main and is passed to the function as an argument. The code works, but when I try to add something to main function (as simple as int i;), the program crashes and the error message is: Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) in the line with "if (*subor==NULL) {" I therefore suppose there's a problem with the way file is stored.

Here's my code:

int funkcia_v (FILE **subor) {
    if (*subor==NULL) {
        printf("File has not been opened yet.\n");
        *subor = fopen("pathtothefile.txt","r");
        if (*subor==NULL) {
            printf("File not opened.\n");
        }
    }
    else {
        printf("File already opened.\n");
    }
    printf("\n");
    return 0;
}

int main() {
    char c;
    //if i type int i; here, the program crashes
    FILE* subor;
    
    printf("Start the function.\n");
    c = getchar();
    
    while (1) {
        if (c=='v') {
            funkcia_v(subor);
        }
        else if (c=='k') {
            break;
        }
        else {
            printf("Unknown key, try again.");
            printf("\n");
        }
        fflush(stdin);
        c = getchar();
    }
    return 0;
}

Any thoughts on what this could be?

CodePudding user response:

So, combining all the constructive comments above, we have this.

#include <stdio.h>
#include <stdlib.h>

int funkcia_v (FILE **subor) {
    if (*subor==NULL) {
        printf("File has not been opened yet.\n");
        *subor = fopen("pathtothefile.txt","r");
        if (*subor==NULL) {
            printf("File not opened.\n");
        }
        else printf("File just opened.\n");
    }
    else {
        printf("File already opened.\n");
    }
    printf("\n");
    return 0;
}

int main() {
    char c;
    int i; // doesn't crash
    FILE* subor = NULL;
    
    printf("Start the function.\n");
    c = getchar();
    
    while (1) {
        if (c=='v') {
            funkcia_v(&subor);
        }
        else if (c=='k') {
            break;
        }
        else if (c!=10) {
            printf("Unknown key %c, try again.",c);
            printf("\n");
        }
        c = getchar();
    }

    if (subor!=NULL) fclose (subor);
    return 0;
}

Note that it passes a pointer of the file pointer to the function.

  • Related