【问题标题】:C- fopen doesn't work properly when I run from makefile当我从 makefile 运行时,C-fopen 无法正常工作
【发布时间】:2020-11-15 13:32:17
【问题描述】:

我编写了一个简单的 makefile 来运行我的代码,因为我被要求这样做作为可交付成果 我在我的代码中使用 fopen,当我从 clion 运行代码时它会找到我通常需要的文件,但是当我从 makefile 运行它时它告诉我它无法找到文件 (我的输出总是打印“找不到 ../a.txt”)

-负责读取的函数(它运行正常,如果我在clion中运行它可以找到文件) 它存在于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);
}

-我的主要(称为 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)

如果你想要我的文件夹的 ls :

 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

【问题讨论】:

  • 可能是因为执行的工作目录不同?
  • 我不明白你的意思
  • 你的makefile在哪里运行 matMultp?还是我误会了?
  • 它们都存在于同一个文件夹中,我只需键入 make 来构建它,然后 ./matMultp 运行它,然后它会显示输出,我编辑了帖子以包含我的 ls文件夹
  • 您可以看到所有文件都存在于同一个文件中,包括 .o 文件、makefile 和 a.txt

标签: c makefile fopen


【解决方案1】:

试试这个,看看你是否有答案:

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);
}

您可能还需要添加#include &lt;unistd.h&gt;

【讨论】:

  • 是的,我现在明白了 clion 和 makefile 有不同的工作目录和不同的可执行位置
  • 把它放在另一个文件夹**所以它们不会冲突,这个文件夹中已经存在属于clion的makefile和可执行文件:D
猜你喜欢
  • 2012-02-26
  • 2013-04-19
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-03
  • 2013-02-21
相关资源
最近更新 更多