我希望我的问题很清楚。我需要用 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/