C assign string from argv[] to char array

前端 未结 1 968
栀梦
栀梦 2021-01-20 07:33

I have the following code which reads an file name from the command line and opens this file:

#include 
#include 
int main(int         


        
1条回答
  •  粉色の甜心
    2021-01-20 08:04

    You must copy the string into the char array, this cannot be done with a simple assignment.

    The simplistic answer is strcpy(filename, argv[1]);.

    There is a big problem with this method: the command line parameter might be longer than the filename array, leading to a buffer overflow.

    The correct answer therefore:

    if (argc < 2) {
        printf("missing filename\n");
        exit(1);
    }
    if (strlen(argv[1]) >= sizeof(filename)) {
        printf("filename too long: %s\n", argv[1]);
        exit(1);
    }
    strcpy(filename, argv[1]);
    ...
    

    You might want to output the error messages to stderr. As a side note, you probably want to choose English or German, but not use both at the same time ;-)

    0 讨论(0)
提交回复
热议问题