Search code examples
cmakefilefopen

C- fopen doesn't work properly when I run from makefile


I wrote a simple makefile to run my code because I was asked to do so as a Deliverable I use fopen in my code,when I run the code from clion It locates the files I need normally, but when I run it from makefile it tells me that it wasn't able to find the files (my output always prints "Couldn't find ../a.txt")

-the function responsible to read (it runs normally and it could find the file if I ran it in clion) it exists in IO.c

void readPar(char *f, int *para) {
    FILE *file = fopen(f, "r");
    if (file == NULL) {
        printf("Couldn't find %s\n", f);
        exit(-1);
    }
    fscanf(file, "row=%d col=%d", &para[0], &para[1]);
    fclose(file);
}

-my main (called matMultp.c)

int main(int argN, char **argS) {
    char files[3][200] = {"../a.txt", "../b.txt", "../c.out"}; //default filenames

    if (argN > 1) { //if some argN was inserted
        for (int i = 1; i < argN; i++) {
            strcpy(files[i-1],"../");
            strcat(files[i-1],argS[i]);
            if(i==3)strcat(files[i-1],".out");
            else strcat(files[i-1],".txt");
        }
    }
    int para1[2] ; 
    readPar(files[0],para1);
    return 0;
}

-makefile

CC=gcc 
CFLAGS=-Wall -pthread -Wextra -g -Wstack-usage=1000 -fstack-usage
LDLIBS= -lpthread

all: matMultp
matMultp: matMultp.o matUtils.o IO.o
matMultp.o: matMultp.c 
matUtils.o : matUtils.c matUtils.h
IO.o : IO.c IO.h 
clean:
    rm -rf $(EXECUTABLE) $(OBJ)

if you want ls of my folder :

 a.txt  b.txt  cmake-build-debug  CMakeLists.txt  

dockDockBuildParams.json  IO.c  IO.h  IO.o  IO.su  

makefile  matMultp  matMultp.c  matMultp.o  matMultp.su  

matUtils.c  matUtils.h  matUtils.o  matUtils.su  tests

Solution

  • Try this and see if the answer dawns onto you:

    void readPar(char *f, int *para) {
        FILE *file = fopen(f, "r");
        if (file == NULL) {
            printf("Couldn't find %s/%s\n", get_current_dir_name(), f);
            exit(-1);
        }
        fscanf(file, "row=%d col=%d", &para[0], &para[1]);
        fclose(file);
    }
    

    You will probably need to add #include <unistd.h> as well.