为什么_ftscanf_s抛出异常而_ftscanf没有?

时间:2014-05-05 22:24:21

标签: c++ c windows exception unicode

我有以下输入文件:

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(不安全版本),程序运行时没有错误。为什么呢?

1 个答案:

答案 0 :(得分: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)
{
}