作为一项任务,我必须使用 c 程序中的 cat 命令将程序的源代码打印到终端中。我知道我需要使用 execl 函数的一些变体来实现这一点,但困扰我的是,要做到这一点,我需要知道可能会改变的文件的路径,所以我想知道是否有办法找到程序内文件的路径。
我尝试运行 pwd 命令来查找当前路径,但无法将结果存储在变量中,我不知道为什么
execl("/bin/pwd", "pwd", NULL);
。
这取决于你如何编译你的程序。如果您使用 gcc,您可能会在源代码旁边找到二进制文件。您应该使用
pwd
函数,而不是执行 getcwd
(正如 @Some 程序员家伙指出的那样)。不要忘记在包含源代码的目录中运行您的程序。
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define YOUR_FILE "source.c"
int main() {
int c;
const char* const_dir = getcwd();
char* destination;
int chars = strlen(const_dir) + strlen(YOUR_FILE);
chars += 1;
destination = malloc(sizeof(char)*chars);
memcpy(destination, const_dir, sizeof(char)*chars);
strcat(destination, "/");
strcat(destination, YOUR_FILE);
FILE *file;
file = fopen(destination, "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
free(file);
free(destination);
return 0;
}