我是编程新手。我想采用一个命令行参数,它是一个文件名并打开该特定文件并将内容复制到另一个文件。我不知道如何将命令行参数转换为字符串或文件指针。我检查了我在网上找到的 strcpy 和 std::string 但它没有用。请帮我。我在下面粘贴了我的代码
#include<string.h>
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
char *inp;
strcpy(inp,argv[1]);
FILE *fp;
char str[5];
//printf("Enter the file name:");
//scanf("%s",fname);
if ((fp= fopen(inp, "r")) == NULL) {
printf("cannot open file");
exit(1);
}
FILE *fp1;
fp1=fopen("out.txt","w+");
while(!feof(fp)) {
fgets(str,4,fp);
printf("%s",str);
fprintf(fp1,"%s",str);
}
fclose(fp);
fclose(fp1);
}
最佳答案
为什么不 char *inp = argv[1];
?
或者更好的是:
fp = fopen(argv[1], "r");
你的代码的问题是这样的:
char *inp;
strcpy(inp,argv[1]);
您正在将 argv[1]
复制到 inp
中,但您不知道 inp
指向什么。如果你真的想走那条路,你必须为 inp
分配内存。
char *inp = malloc(strlen(argv[1]) + 1); /* allocate enough for the string and null-terminator */
strcpy(inp,argv[1]); /* copy the contents */
请记住之后 free()
。
附言从不使用while(!feof(fp))
。只需使用 while(fgets(str,4,fp))
。
参见 this question了解更多信息。
关于在 C 中将命令行参数转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32960125/