2009-07-21 29 views
1

我学习C++,然后我在寻找一些代码学习在该地区的东西,我喜欢:文件I/O,但我想知道我可以调整我的用户键入代码,他希望看到的文件,就像在wget的,但我的程序是这样的:输入文件名时,执行中的程序在C++

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; 
} 

谢谢!

+1

我意识到Stackoverflow对所有人开放,所以它会是一个自由的信息交换,但是你会问很多问题,简单的谷歌搜索会回答。 – jkeys 2009-07-21 03:24:35

+0

我之前在Google中搜索过! – 2009-07-21 03:27:47

+2

在这种情况下,建议您使用stat函数来获取文件大小。如果成功,它会填充“struct stat”,然后您可以通过st_size来检查文件大小的值。上面的代码没有检查文件是否存在。无论如何,只是挑剔...重点是打开从命令行传入的文件名:) – Matt 2009-07-21 03:28:42

回答

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; 
} 
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]); 
     ... 
    } 
} 

否te,argv [0]是一个指向你自己程序名字的字符串。

相关问题