2009-07-21 55 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]是一個指向你自己程序名字的字符串。

相關問題