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

查看:27
本文介绍了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;
}

此示例有效,但我想将命令行中的字符串写入字符数组并将该字符数组传递给 fopen(),但出现编译器错误错误:赋值给数组类型文件名 = 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天全站免登陆