【问题标题】:use file as an input to a compiled c program使用文件作为已编译 c 程序的输入
【发布时间】:2019-05-11 09:23:24
【问题描述】:

在我的程序中,我得到了 2 个路径,一个是包含各种文件的目录的路径。 每当我找到一个 c 文件时,我都会编译它。 第二个路径是输入 txt 文件。 让我们这样说:

home/dvir/workspace/assignment1/students/  -(directory)
home/dvir/workspace/tests/input1.txt/ -(input txt file)

这是我的代码的一部分:

void listdir(const char *name, int indent)
{
    char path[80];
    char cmd[4096 + 2*80];

    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(name)))
        return;

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            char path[1024];
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                continue;
            snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
            printf("%*s[%s]\n", indent, "", entry->d_name);
            listdir(path, indent + 2);
        } else {
            printf("%*s- %s\n", indent, "", entry->d_name);
            snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); 
            snprintf(cmd, sizeof(cmd), "gcc -c %s -o %s.o", path, path);
            if (system(cmd) == 0) {
                printf("Compiled %s to %s.o\n", path, path);
            }
        }
    }
    closedir(dir);
}

它递归遍历目录并编译所有文件,我将 input.txt 目录保存在 char 数组中并将其称为输入。 现在让我们假设我编译了一个 c 程序并获得了 ashly.c.o 文件。 如何使用 txt 文件作为输入运行该程序?(以及如何实际访问该编译程序?) 例如: 假设 ashly.c.o 从用户那里获得 2 个数字并将它们相乘。 我想使用 input.txt 文件作为这两个数字 并将输出保存为一个新的 txt 文件。(以便我以后可以阅读) 我找到了一些 ofthis 的答案,但在我的情况下,我不想使用 freopen() 函数(只是打开),我需要一种从我的程序访问编译文件的方法...... 任何帮助将不胜感激。

【问题讨论】:

  • 你想重新发明make 吗?
  • 我有点不清楚你在问什么,但据我所知,你还没有生成任何可执行程序。您需要将 .o 文件链接在一起(或者如果每个 c 文件都是一个完整的程序,则需要在没有 -c 选项的情况下进行编译)
  • 您通常无法运行 .o 文件。但是你可以用它们制作一个库,然后dlopen()it、dlsym()-link 将单个 .o 提供的函数链接到库中并调用这些函数。
  • 也许你可能想要pipe(7)-s

标签: c file compilation operating-system system-calls


【解决方案1】:

forkexec 可以为所欲为。

if (fork() == 0) {
    int fd = open("/path/to/your/input", O_RDONLY);
    dup2(fd, 0);
    // execl or so
    exec("/path/to/the/created.o", ...);
}

【讨论】:

  • 你能解释一下它是如何工作的吗?
  • gcc 编译文件后(我猜-c 选项应该被删除),fork() 和 exec() 将创建一个执行刚刚编译的 .o 文件的新进程。另见redirect-execstdinexec 之前被dup2 重定向到输入文件(我不知道您是否决定使用stdin 作为输入,如果不是,请删除该行)。有关forkexec 的更多信息,请访问APUE、CSAPP 或here
  • 谢谢,我现在确实理解了这个想法,还有一件事,我不断收到警告:函数'exec'的隐式声明,虽然我确实包含了 unistd.h.n你有什么关于可能是什么原因的想法?(我试图在不更改任何内容的情况下编译代码)
  • #include <stdlib.h> 可能会有所帮助(但如果链接器没有抛出错误,尽管出现警告,程序仍会运行)。
  • 我不知道是不是链接器,但是程序抛出 /tmp/ccUPN2ER.o: In function main': program.c:(.text+0x42): undefined reference to exec' collect2: error: ld returned 1 exit status
猜你喜欢
  • 1970-01-01
  • 2011-08-05
  • 2011-08-10
  • 2021-11-23
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多