2013-03-22 82 views
0

我有一個文件,我想要獲取文件的大小。我只能使用_wfopen_wfopen_s打開文件,因爲我的文件路徑類型爲std::wstring在C++中獲取文件大小

FILE* p_file = NULL; 
p_file=_wfopen(tempFileName.c_str(),L"r"); 
fseek(p_file,0,SEEK_END); 

但我得到一個錯誤

error C2220: warning treated as error - no 'object' file generated 
+2

這是一個編譯錯誤,你有一個警告已被視爲錯誤。嘗試修復警告原因或降低警告級別。這與文件開放無關直接 – 2013-03-22 10:25:42

+0

如何修復警告原因? – TVSuser1654136 2013-03-22 10:26:39

+0

你可以擺脫警告作爲beeing這樣處理爲錯誤http://stackoverflow.com/questions/2520853/warning-as-error-how-to-rid-these – banuj 2013-03-22 10:26:44

回答

0

擺脫你的錯誤信息,你需要修復所產生的警告的問題。

如果您編譯此代碼:

#include "stdafx.h" 
#include <string> 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    FILE* p_file = NULL; 
    std::wstring tempFileName = L"c:\\test.txt"; 
    p_file=_wfopen(tempFileName.c_str(),L"r"); 

    if(!p_file) 
    { 
     perror("Open failed."); 
     return 0; 
    } 

    fseek(p_file,0,SEEK_END); 
    fclose(p_file); 

    return 0; 
} 

你會得到這樣的警告:

警告C4996: '_wfopen':此函數或變量可能是不安全的。考慮使用_wfopen_s代替。要禁用棄用,請使用_CRT_SECURE_NO_WARNINGS。詳細信息請參見在線幫助。

所以,聽它說什麼,並執行以下操作:

#include "stdafx.h" 
#include <string> 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    FILE* p_file = NULL; 
    std::wstring tempFileName = L"c:\\test.txt"; 
    _wfopen_s(&p_file, tempFileName.c_str(),L"r"); 

    if(!p_file) 
    { 
     perror("Open failed."); 
     return 0; 
    } 

    fseek(p_file,0,SEEK_END); 
    fclose(p_file); 

    return 0; 
} 

有通過將_CRT_SECURE_NO_WARNINGSProject Properties關閉該警告的方式 - >C/C++ - >Preprocessor - >Preprocessor Definitions,但你應該總是喜歡安全的替代這些功能。

另外,在fseek之前,您應該檢查您的p_file指針是否爲NULL