0

當我們在Visual Studio 2013(C++控制檯應用程序),Os-Winsever2008(64位)中使用fscanf_s方法時,文件指針提前讀取一個或兩個字節的數據。 例如:在讀取文本文件時,文件的第二行是「Administartor」,但fscanf_s()將該單詞作爲「dministrator」返回。 請幫我解決這個問題。 代碼是使用Visual Studio 2008fscanf_s在Winserver2008中無法正常工作VS2013 64位

FILE* pFile; 
pFile = NULL; 
string strFile = "E:\\10_Products.lrf"; 
fopen_s(&pFile, strFile.c_str(), "r"); 
char szTemp[256]; 
string strTemp = ""; 
if (NULL != pFile) 
{ 
    while (!feof(pFile)) 
    { 
     nRet = fscanf_s(pFile, "%s", szTemp); 
     if (EOF == nRet) 
     { 
      cout << "EOF detected"; 
     } 
    } 
    return 0; 
} 

10_Products.lrf文件的格式如下工作正常的Windows XP 32位。

[OPERATOR_LEVEL] 
Administrator 
+2

向我們顯示您的代碼。 –

+0

示例代碼 \t FILE * pFile; \t pFile = NULL; \t string strFile =「E:\\ 10_Products.lrf」; \t fopen_s(&pFile,strFile.c_str(),「r」); \t char szTemp [256]; \t string strTemp =「」; \t如果(NULL = PFILE!) \t \t { \t \t而(FEOF(PFILE)!) \t \t { \t \t \t NRET = fscanf_s(PFILE, 「%s」 時,szTemp); \t \t \t如果(EOF == NRET) \t \t \t { \t \t \t \t COUT << 「EOF檢測到的」; \t \t \t} \t} \t返回0; } –

+0

你應該編輯你的文章,而不是將其添加爲評論 –

回答

0

從文檔上fscanf_s(),http://msdn.microsoft.com/en-us/library/6ybhk9kc.aspx

The main difference between the secure functions (with the _s suffix) and the older functions is that the secure functions require the size of each c, C, s, S and [ type field to be passed as an argument immediately following the variable. For more information, see scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l and scanf Width Specification. 

而且http://msdn.microsoft.com/en-us/library/w40768et.aspx

Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or [. The buffer size is passed as an additional parameter immediately following the pointer to the buffer or variable. For example, if reading a string, the buffer size for that string is passed as follows: 

char s[10]; 

scanf("%9s", s, 10); 

所以你應該把它像這樣:

fscanf_s(FP, 「%80s」,cmd,sizeof(cmd));

+0

感謝您的更新。它工作正常....非常感謝你... –

+0

如果這個答案對你有幫助,你能否把它標記爲答案? – CreativeMind