2014-05-05 57 views
1

我有以下輸入文件:爲什麼_ftscanf_s拋出異常並且_ftscanf不會?

1 100000 hajs ssaa 25 
2 150000 sdsd Assso 22 
... 

和下面的程序:

#define _UNICODE 
#define UNICODE 

#define _CRT_SECURE_NO_WARNINGS 

#include <Windows.h> 
#include <tchar.h> 
#include <stdio.h> 
#include <stdlib.h> 


#define MAX_CHARS  30 

typedef struct student 
{ 
    WORD identifier; 
    DWORD registerNumber; 
    TCHAR surname[MAX_CHARS + 1]; 
    TCHAR name[MAX_CHARS + 1]; 
    WORD mark; 

} student_t, *student_ptr; 


int _tmain(DWORD argc, LPTSTR argv[]) 
{ 
    FILE* fileIn; 
    errno_t error; 
    student_t student; 

#ifdef UNICODE 
    error = _wfopen_s(&fileIn, argv[1], L"r"); 
#else 
    error = fopen_s(&fileIn, argv[1], "r"); 
#endif 

    if (error) 
    { 
     _ftprintf(stderr, _T("Unable to open %s\n"), argv[1]); 
     exit(EXIT_FAILURE); 
    } 

    while (_ftscanf_s(fileIn, _T("%hu %lu %s %s %hu"), &student.identifier, &student.registerNumber, 
     student.surname, student.name, &student.mark) != EOF) 
    { 

    } 

    fclose(fileIn); 

    return 0; 
} 

現在,如果我用_ftscanf_s我有以下異常:

First-chance exception at 0x53871CA4 (msvcr110d.dll) in vsproj.exe: 0xC0000005: Access violation writing location 0x002F0000. 

而如果我使用_ftscanf(不安全版本)程序運行時沒有錯誤。爲什麼?

+0

很有可能是因爲你忘了提供所需要用'%s'與['* scanf_s()'](HTTP長度參數:// MSDN。 microsoft.com/en-us/library/6ybhk9kc.aspx)函數。 –

回答

1

您必須指定%s所需的長度參數。請嘗試使用_countof宏:

while (_ftscanf_s(fileIn, _T("%hu %lu %s %s %hu"), &student.identifier, &student.registerNumber, 
     student.surname, _countof(student.surname), student.name, _countof(student.name), &student.mark) != EOF) 
{ 
} 
相關問題