C - main() 命令行参数

标签 c command-line parameters program-entry-point

这是一个非常基本的问题,但我在任何地方都找不到明确的答案。 我了解 main 的参数,就它们所指的而言:

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

其中 argc 指命令行参数的数量,argv 指保存每个字符串的数组。我从 .c 文件创建了源代码的 exe 文件,但没有使用命令提示符的经验,也不了解命令行参数的语法。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main(int argc, char *argv[])
{
    FILE *infile, *outfile;
    int iochar;

    if(argc != 3){
        printf("Usage: filename infile outfile\n");
        exit(1);
    }

    if((infile = fopen(argv[1], "r")) == NULL){
        printf("Can't open input file.\n");
        exit(1);
    }

    if((outfile = fopen(argv[2], "w")) == NULL){
        printf("Can't open output file.\n");
        exit(1);
    }

    while((iochar = getc(infile))!=EOF){
        putc(iochar, outfile);
    }

    fclose(infile);
    fclose(outfile);

    printf("You've reached the end of the program.\n"); 

    return;
}

前面的代码应该采用 3 个参数,并将第二个参数的内容复制到第三个参数的位置。我必须做什么才能发生这种情况?

最佳答案

您可以在 VS 项目的“调试”属性中设置命令行参数。

don't understand the syntax of the command line arguments.

命令行参数的语法细节取决于解释它们的程序...VS、Windows 快捷方式、Windows cmd、bash 等...但通常它只是一个由空格分隔的项目列表。如果项目本身包含空格、引号或其他特殊字符,那么您需要注意您所使用的解释器的规则。

命令行参数的语义由您的程序定义...在本例中,第一个参数是输入文件的名称,第二个参数是输出文件的名称。

printf("Usage: filename infile outfile\n");

这不是一个好的用法消息...“文件名”应该是您的程序的名称,通常是 argv[0] 的值。因此:

printf("Usage: %s infile outfile\n", argv[0]);

关于C - main() 命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20463238/

相关文章:

c++ - 转置一维数组

c - 在 C 中类似 Yacc 的解析器中重复 ‘extern’

c# - 无法在 C# 中正确获取命令行参数

apache - 使用命令行更改文档根目录

sql - GROUP BY 在 SQL 中使用参数

c - Serial.println(Serial.available());改变 Arduino 代码的行为

cmd- 逗号分隔参数 比起空格?

pointers - 如何使用golang将结构的方法作为参数传递给另一个函数

jsp - Struts2:如何从 <jsp:include> 读取参数

使用 scanf 而不是 var=0 后,C 程序停止工作