使用变量在 C 文件中调用 bash 命令

标签 c linux bash

我希望我的问题很清楚。我需要用 C 读取一个文件,存储文件的内容,然后在 bash 脚本中使用这个变量。

例如,有一个名为“test.txt”的文件,其中包含“aaa”。这是 C 中的调用:

#include <signal.h>
#include <time.h>

char ch;
FILE *fp;

int main(int argc, char **argv) {
    fp = fopen("test.txt", "r");
    char contents[9] = "";
    if( fp == NULL ) {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
    }

    int i = 0;
    while( ( ch = fgetc(fp) ) != EOF ) {
      contents[i]=ch;
      i++;
    }
    contents[9]=0;
    fclose(fp);
    system( "echo 'hi'");
    puts(contents);
}

现在我需要使用 bash 脚本来读取名称中包含“aaa”的文件名。

system("cat /home/user/$contents.txt");

我曾尝试寻找其他一些解决方案,但到目前为止我只遇到过 popen 而未能实现。如果我使用 bash,它是一个非常简单的单行代码,这就是我尝试实现它的原因。还有其他选择吗?

最佳答案

如果我对你的问题理解正确,也许你可以通过环境变量将 contents 传递给 bash。

http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access

这是一个示例代码:

#include <stdlib.h>
int main(){
  char * message = "hello";
  setenv("contents", message, 1);
  system("echo $contents");
}

这个脚本的输出是

hello

关于使用变量在 C 文件中调用 bash 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46110941/

相关文章:

java - if 和 return 或 while 什么更快最好?

c - C 中的链表 : Having issues with entering string and displaying it

c - fork () 和 execlp () , execlp() 之前的 printf 没有被执行

bash - echo -e 反斜杠转义在 sh 中不被尊重

bash - 如何使 bash tab 补全表现得像 vim tab 补全并循环匹配匹配项?

linux - 如何在带双引号的ssh命令中处理单引号

c - 如何使用 C 抓取网页?

c - 汇编:在调用函数之前加载有效地址的目的?

linux - 使用文件 url 访问文件

linux - shell脚本单独列出目录中的文件名并重命名