将字符串添加到 C 中给定的命令行参数

add string to given command line argument in C

你好,我刚开始用 C 编程,我正在尝试读取一个文件并将文件名作为不带结尾 .txt 的参数。我想在我的代码中添加 .txt :./myexample.exe file

如果我使用 file.txt 没有问题,但我不知道如何更改 argv[1] 我试过 char *n = argv[1] + ".txt";它不起作用,我什么都不知道..

int main(int argc, char* argv[]) {
      char *n = argv[1] +".txt";
      FILE *fp1;
      fp1 = fopen(n , "r");

这就是我使用 char *n = argv[1]+".txt"

得到的结果

error: invalid operands to binary + (have 'char *' and 'char *')

在您的代码中,

 char *n = argv[1] +".txt";

并不像你想象的那样。在 C 中,+ 不能用于连接 字符串

仅供参考,来自 C11,章节 §6.5.6

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)

两个操作数都不能是指向对象的指针类型。

如果您打算连接 字符串 ,请使用 strcat(),但请确保

  • 目的地是可修改的(尝试修改字符串文字是 UB)
  • 目的地有足够的 space 来包含最终结果(较短的目的地会导致再次调用 UB 访问越界内存)。

不能用 + 连接字符串。使用 strcpy 和 strcat:

char n[256];
strcpy(n, argv[1]);
strcat(n, ".txt");

确保 n 足够大以容纳文件名 + 扩展名。

安全地做这件事有点烦人:您需要小心制作一个足够大的 char 数组来容纳整个字符串。一种方式:

size_t arglen=strlen(argv[1]);
char* filename=malloc(arglen+5); //Enough to hold the whole string
strcpy(filename,argv[1]);
strcat(filename,".txt");

以后一定要free指针。