Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C语言中读取argv_C - Fatal编程技术网

在C语言中读取argv

在C语言中读取argv,c,C,我想读取三个文件的路径(例如,“../c/.file”)和一个来自argv[]的长值,并将它们绑定到三个已经创建的char*,以及一个名为num的长值 以下是我的主要功能: int main(int argc, char* argv[]){ char* file1 = NULL; char* file2 = NULL; char* file3 = NULL; long num = 0; //copy the file paths to the char

我想读取三个文件的路径(例如,“../c/.file”)和一个来自argv[]的长值,并将它们绑定到三个已经创建的char*,以及一个名为num的长值

以下是我的主要功能:

int main(int argc, char* argv[]){

    char* file1 = NULL;
    char* file2 = NULL;
    char* file3 = NULL;
    long num = 0;

    //copy the file paths to the char*'s
    strcpy(file1, argv[1]);
    strcpy(file2, argv[2]);
    strcpy(file3, argv[3]);
    // convert from string to long int
    num = strtol(argv[4],NULL,0);

}
但是这不起作用,文件的文件名和long的值不会像它们应该的那样最终出现在变量上

我怎样才能解决这个问题


在我的程序中,我检查argc值以确保没有传递错误的内容,但在这里,我以这种方式编写函数只是为了说明我的问题。

不要将strcp复制到不指向已分配内存的指针中。相反,只需将它们设置为argv数组中的指针,而argv数组已经指向分配的内存。像这样:

int main(int argc, char *argv[])
{
    if (argc < 5)
        fprintf(stderr, "usage: %s <file1> <file2> <file3> <num>\n", argv[0]), exit(1);

    char *file1 = argv[1];
    char *file2 = argv[2];
    char *file3 = argv[3];
    long  num   = strtol(argv[4], NULL, 0);

    /* Do stuff */

    return 0;
}
intmain(intargc,char*argv[])
{
如果(argc<5)
fprintf(stderr,“用法:%s\n”,argv[0]),退出(1);
char*file1=argv[1];
char*file2=argv[2];
char*file3=argv[3];
long num=strtol(argv[4],NULL,0);
/*做事*/
返回0;
}

如果要从argv复制字符串,则必须在程序中为这些字符串分配内存。比如说

int main(int argc, char* argv[])
{
    char *file1, *file2, *file3;
    long num = 0;

    if ( argc > 1 )
    {
        file1 = malloc( strlen( argv[1] ) + 1 ); 
        strcpy( file1, argv[1] );
    }

    if ( argc > 2 )
    {
        file2 = malloc( strlen( argv[2] ) + 1 ); 
        strcpy( file2, argv[2] );
    }

    if ( argc > 3 )
    {
        file3 = malloc( strlen( argv[3] ) + 1 ); 
        strcpy( file3, argv[3] );
    }

    if ( argc > 4 )
    {
        num = strtol( argv[4], NULL, 0 );
    }

    //...

有些时候,我们忽略了一些争论,因此我们需要检查是否所有的争论都存在 论据是否给出

  main(int argc,char *argv[])
  {
         if(argc != 5)
            printf("Error message");
         else{
             //perofmr your operation what you want
             }
  }

您正在尝试将
strcpy
您的
argv
字符串复制到
NULL
地址。要么按照@jschultz410在回答中所说的去做,要么使用
strdup
而不是
strcpy
。@潜伏者:请注意
strdup
不是标准的C。strdup是posix标准的。我们为什么要分配字符串长度+1字节?(malloc(strlen..)+1@user3019799字符串还包括未被函数strlen计数的终止零字符'\0'。