C将字符串从argv []分配给char数组 [英] C assign string from argv[] to char array

查看:257
本文介绍了C将字符串从argv []分配给char数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,该代码从命令行读取文件名并打开该文件:

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

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
    FILE *datei;
    char filename[255];

    //filename = argv[1];
    //datei=fopen(filename, "r");
    datei=fopen(argv[1], "r");
    if(datei != NULL)
        printf("File opened");
    else{
        printf("Fehler beim öffnen von %s\n", filename);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

此示例有效,但我想将命令行中的字符串写入char数组,并将该char数组传递给fopen(),但出现编译器错误 Error: assignment to expression with array type filename = argv[1];

This example works, but I want to write the string from the command line to the char array and pass that char array to to fopen(), but i get the compiler error Error: assignment to expression with array type filename = argv[1];

此错误是什么意思,我该怎么解决?

What does this error mean and what can I do to fix it?

推荐答案

您必须将字符串复制到char数组中,这不能通过简单的赋值完成.

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

简单的答案是strcpy(filename, argv[1]);.

此方法存在一个大问题:命令行参数可能比filename数组长,从而导致缓冲区溢出.

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

因此,正确答案是:

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]);
...

您可能希望将错误消息输出到stderr. 附带一提,您可能要选择英语或德语,但不要同时使用两者;-)

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 ;-)

这篇关于C将字符串从argv []分配给char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆