c - 带系统函数的 C 程序中的大括号扩展

标签 c bash system brace-expansion

我尝试了该命令

cat tmp/file{1..3} > newFile

并且工作完美

但是当我编译并执行以下c程序时

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main() {
   char command[40];
   int num_of_points = 3;
   sprintf(command,"cat tmp/file{1..%d} > file.Ver",num_of_points);
   system(command);
}

消息

cat: tmp/file{1..3}: No such file or directory

出现

系统似乎没有进行大括号扩展

最佳答案

It seems like system does not make brace expansion

问题是 system() 调用的 shell,它不是 Bash,而是另一个不支持大括号扩展的 shell。


您仍然可以使用选项-c调用bash,以便将bashsystem()一起使用。例如:

system("bash -c 'echo The shell is: $SHELL'")

bash 本身将在另一个 shell 之上运行(即:shell system() 调用),但 echo 命令将绝对在 Bash 中运行。

通过在代码中应用相同的原则:

sprintf(command,"bash -c 'cat tmp/file{1..%d} > file.Ver'",num_of_points);

将创建您需要传递给system()的正确命令字符串,以便命令cat tmp/file{1..%d} > file.Ver 在 Bash 中运行并执行大括号扩展。

关于c - 带系统函数的 C 程序中的大括号扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47509608/

相关文章:

c - SSE 字节和半字交换

c++ - 停止使用 libpcap 捕获数据并将其保存在文件中

c - C语言中如何设置位

linux - 为什么 bc 和 args 不能在一行中一起工作?

linux - 为什么 tar -cf ${PWD}.bz2 不产生任何输出?

perl - 仅在外部应用程序存在时运行的最佳方式

c++ - GetSystemInfo 不起作用

c - 如何引用在 .h 文件中初始化的二维数组并在 .c 函数中使用它?

bash - 每次启动时手动启动 HDFS?

c - sysv共享内存,会自动销毁吗?