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

Nat*_*pos 1 c++ file-io

我正在学习C++,然后我正在寻找一些代码来学习我喜欢的领域:文件I/O,但我想知道我如何调整我的代码为用户输入他想要看的文件,就像在wget中一样,但我的程序是这样的:

C:\> FileSize test.txt
Run Code Online (Sandbox Code Playgroud)

我的程序代码在这里:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Kan*_*ann 6

在下面的示例中,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;
}
Run Code Online (Sandbox Code Playgroud)