C语言中的系统命令,如何在一个字符串内传递一个指针在“”之间

时间:2013-10-10 10:53:38

标签: c string pointers

我正在尝试在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命令处理

2 个答案:

答案 0 :(得分:1)

只需将两者合并为一个字符串即可。 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;
}

答案 1 :(得分:0)

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

int 
main(void)
{
    const char *file = "/home/shailendra/sampleprograms/C/output.txt";

    char buf[500];

    if (snprintf(buf, sizeof buf, "gzip -r '%s'", file) >= sizeof buf) {
        /* command could not be composed, too long */
    } else {
        system(buf); 
    }

    return 0;
}