【问题标题】:Why _ftscanf_s throws exception and _ftscanf does not?为什么 _ftscanf_s 会抛出异常而 _ftscanf 不会?
【发布时间】:2014-06-22 08:54:24
【问题描述】:

我有以下输入文件:

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

【问题讨论】:

  • 很可能是因为您忘记使用*scanf_s() 函数提供%s 所需的长度参数。

标签: c++ c windows exception unicode


【解决方案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)
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2021-04-28
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多