OiO.lk Blog C# Check if the file was opened in C
C#

Check if the file was opened in C


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?



You need to sign in to view this answers

Exit mobile version