访问冲突,同时使用fscanf_s [英] Access violation while using fscanf_s

查看:1135
本文介绍了访问冲突,同时使用fscanf_s的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读特定格式的文件,所以我用fscanf_s和while循环。但只要fscanf_s被处理时,程序崩溃与访问冲突(0000005)。

I want to read a file in a specific format, so I use fscanf_s and a while loop. But as soon as fscanf_s is processed, the program crashes with an access violation (0xC0000005).

这里的code:

FILE *fp;
errno_t err = fopen_s(&fp, "C:\\data.txt", "r");

if (err != 0)
    return 0;

int minSpeed = 0;
int maxSpeed = 0;
char axis = '@';

while(!feof(fp)) 
{
    int result = fscanf_s(fp, "%c;%d-%d\n", &axis, &minSpeed, &maxSpeed);

    if (result != 3)
        continue;
}

fclose(fp);

该文件的内容是基于行的,例如:

The content of the file is line based, for example:

-;10000-20000
X;500-1000
S;2000-2400

有人可以帮我吗?

Can somebody help me?

推荐答案

显然,的 fscanf_s()需要变量的地址后,一个尺寸参数

Apparently, fscanf_s() needs a size parameter after the address of the variable

fscanf_s(fp, "%c;%d-%d\n", &axis, 1, &minSpeed, &maxSpeed);
/* extra 1 for the size of the   ^^^ axis array */

不过,我建议你不要使用 * _ S 功能:它们比显然命名函数更糟---他们需要相同的检查,让你感到安全的时候你不是。我建议你​​不要使用他们,因为虚假的安全感,事实上,他们并非适用于许多实现让你的程序只有在可能的机器的一个有限的子集。

But I suggest you do not use the *_s functions: they are worse than the plainly named functions --- they require the same checks and make you feel safe when you aren't. I suggest you don't use them because of false sense of security and the fact they are not available on many implementations making your programs work only in a limited subset of possible machines.

使用普通的fscanf()

Use plain fscanf()

fscanf(fp, "%c;%d-%d\n", &axis, &minSpeed, &maxSpeed);
/* fscanf(fp, "%1c;%d-%d\n", &axis, &minSpeed, &maxSpeed); */
/* default 1   ^^^    same as for fscanf_s                 */


和您的的feof()是错误的使用。结果
的fscanf()时有错误(档案结尾或匹配故障或读取错误...)。


And your use of feof() is wrong.
The fscanf() returns EOF when there is an error (end-of-file or matching failure or read error ...).

您可以使用的feof(),以确定为什么的fscanf()失败,不检查它是否会失败下一次它被调用。

You can use feof() to determine why fscanf() failed, not to check whether it would fail on the next time it is called.

/* pseudo-code */
while (1) {
    chk = fscanf();
    if (chk == EOF) break;
    if (chk < NUMBER_OF_EXPECTED_CONVERSIONS) {
        /* ... conversion failures */
    } else {
        /* ... all ok */
    }
}
if (feof()) /* failed because end-of-file reached */;
if (ferror()) /* failed because of stream error */;

这篇关于访问冲突,同时使用fscanf_s的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆