命令行参数,读取文件

use*_*329 11 c arguments file command-line-arguments

如果我进入命令行C:myprogram myfile.txt

如何在程序中使用myfile.我是否必须扫描它或是否有任意方式访问它.

我的问题是如何在我的程序中使用myfile.txt.

int
main(){
    /* So in this area how do I access the myfile.txt 
    to then be able to read from it./*
Run Code Online (Sandbox Code Playgroud)

sri*_*eak 16

您可以将其int main(int argc, char **argv)用作主要功能.

argc - 将是您的程序的输入参数的计数.
argv - 将是指向所有输入参数的指针.

所以,如果您输入C:\myprogram myfile.txt运行程序:

  • argc 将是2
  • argv[0]会的myprogram.
  • argv[1]会的myfile.txt.

更多细节可以在这里找到

要阅读文件:
FILE *f = fopen(argv[1], "r"); // "r" for read

要在其他模式下打开文件,请阅读此内容.