我正在尝试在 C 代码中使用 system
命令,我想执行 gzip -r 命令将 .txt 文件转换为 .txt.gz。现在文件的名称为转换后存储在指针中,并根据提供的文档 at this link ,我们需要像这样将gzip的整个命令复制到一个字符串
char gzip[100];
strcpy(gzip,"gzip -r /home/abc/xyz/pqr.txt");
现在我遇到一个问题,文件 pqr.txt 的名称存储在指针中。那么我如何将该指针传递给在 gzip 中复制的字符串,然后传递给系统命令。
这是我正在使用的完整代码。
#include<stdio.h>
#include<stdlib.h>
int main()
{ char *ptr1= "gzip -r/home/shailendra/sampleprograms/C/output.txt"; //working
//char *ptr2 = "/home/shailendra/sampleprograms/C/output.txt"; // pointer used tyo store th name of file
//char *ptr = " gzip -r *ptr2.sstv"; //not working
int i;
char tar[50];
system(ptr1); //working
system(ptr); //not working
return 0;
}
因此,我不是先初始化数组,然后将字符串复制到数组,然后传递给系统命令,而是将字符串传递给指针,然后将该指针传递给系统命令。
所以我主要关心的是如何将存储在字符串指针中的文件名传递给字符串,以便它由system
命令处理
最佳答案
只需将两者合并为一个字符串即可。 sprintf
可以帮助您:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *ptr2 = "/home/shailendra/sampleprograms/C/output.txt"; // pointer used tyo store th name of file
char *ptr = " gzip -r '%s'";
int i;
char buf[500];
sprintf(buf, ptr, ptr2);
system(buf); //working
return 0;
}
关于c - C 中的系统命令,如何在 ""之间的字符串内传递指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293819/