代码之家  ›  专栏  ›  技术社区  ›  Nathan Campos

在C++中执行程序时输入文件名

  •  1
  • Nathan Campos  · 技术社区  · 16 年前

    我在学习 C++ ,然后我在搜索一些代码,以便在我喜欢的领域中学习一些东西: 文件输入输出 ,但我想知道如何调整我的代码,以便用户键入他想查看的文件,如 WGET 但是我的程序是这样的:

    C:\> FileSize test.txt
    

    我的程序代码如下:

    // obtaining file size
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main () {
      long begin,end;
      ifstream myfile ("example.txt");
      begin = myfile.tellg();
      myfile.seekg (0, ios::end);
      end = myfile.tellg();
      myfile.close();
      cout << "size is: " << (end-begin) << " bytes.\n";
      return 0;
    }
    

    谢谢!

    3 回复  |  直到 16 年前
        1
  •  6
  •   KPexEA    16 年前

    在下面的示例中,argv包含命令行参数,作为以空结尾的字符串数组,argc包含一个整数,告诉您传递了多少参数。

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main ( int argc, char** argv )
    {
      long begin,end;
      if( argc < 2 )
      {
         cout << "No file was passed. Usage: myprog.exe filetotest.txt";
         return 1;
      }
    
      ifstream myfile ( argv[1] );
      begin = myfile.tellg();
      myfile.seekg (0, ios::end);
      end = myfile.tellg();
      myfile.close();
      cout << "size is: " << (end-begin) << " bytes.\n";
      return 0;
    }
    
        2
  •  3
  •   lavinio    16 年前

    main() 获取参数:

    int main(int argc, char** argv) {
        ...
        ifstream myfile (argv[1]);
        ...
    }
    

    您还可以变得聪明,并为命令行上指定的每个文件循环:

    int main(int argc, char** argv) {
        for (int file = 1; file < argc;  file++) {
            ...
            ifstream myfile (argv[file]);
            ...
        }
    }
    

    注意argv[0]是一个指向您自己程序名称的字符串。

        3
  •  1
  •   jkeys    16 年前

    main接受两个参数,您可以使用它们来完成此操作。看到这个:

    Uni ref

    MSDN reference (has VC specific commands