c - C 中的系统命令,如何在 ""之间的字符串内传递指针

标签 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命令处理

最佳答案

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

相关文章:

java - 如何找到未知子串的连续重复

c - 将包含另一个结构的结构传递给 pthread_create

objective-c - NSArray 的字符串排序问题

c - 在 void * 之上实现一个结构类型

关闭子进程中打开的套接字

通过引用调用、const 正确性和对引用结构的读写访问 - 未定义的行为

c - 为什么使用 snprintf 会出现运行时错误?

c++ - 指向(定义了指针数组)字符串的指针数组 : Are the strings stored sequential in memory?

C++ 初始化程序不断地在同一内存位置创建新对象

c - 如何在C中正确访问数组成员?