我正在学习 C ++ ,然后我正在寻找一些代码来学习我喜欢的领域:文件I / O ,但我想知道我如何调整我的代码,为用户键入他想要查看的文件,例如 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;
}
谢谢!
答案 0 :(得分: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;
}
答案 1 :(得分:3)
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]是一个指向您自己程序名称的字符串。
答案 2 :(得分:1)