c使用freopen和argv在终端创建文件[1]

时间:2022-02-14 19:22:56

I'm trying to create a file using terminal in Unix. My code is below. I know for a fact argv[1] is picking up the data from the terminal screen, so for example when i do ./a.out newfile.txt, argv[1] has the value newfile.txt

我正在尝试使用Unix中的终端创建一个文件。我的代码如下。我知道argv [1]从终端屏幕获取数据,所以例如当我执行./a.out newfile.txt时,argv [1]的值为newfile.txt

When I run the command ls to check my directory, the file is called argv[1]. Do i need to use some form of pointers to succeed in what I'm attempting?

当我运行命令ls来检查我的目录时,该文件名为argv [1]。我是否需要使用某种形式的指针来成功实现我的目标?

Regards

int main (int argc, char* argv[])
{
  printf("File to create: %s \n", argv[1] );
  freopen("argv[1]", "w+", stdout);
  return 0;
}

2 个解决方案

#1


2  

You are telling freopen to create a file called "argv[1]", as a char* (as a "string" if you will). To actually use the argv[1] argument to create a file as per the first argument given to your program, don't quote the argv[1]:

你告诉freopen创建一个名为“argv [1]”的文件,作为char *(如果你愿意的话,作为“字符串”)。要实际使用argv [1]参数根据程序的第一个参数创建文件,请不要引用argv [1]:

  freopen(argv[1], "w+", stdout);

#2


1  

Just remove quotes.

只需删除引号即可。

freopen(argv[1], "w+", stdout);

#1


2  

You are telling freopen to create a file called "argv[1]", as a char* (as a "string" if you will). To actually use the argv[1] argument to create a file as per the first argument given to your program, don't quote the argv[1]:

你告诉freopen创建一个名为“argv [1]”的文件,作为char *(如果你愿意的话,作为“字符串”)。要实际使用argv [1]参数根据程序的第一个参数创建文件,请不要引用argv [1]:

  freopen(argv[1], "w+", stdout);

#2


1  

Just remove quotes.

只需删除引号即可。

freopen(argv[1], "w+", stdout);