Access Violation Using fscanf_s

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).

Here is the 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 contents of the file are line-based, for example:

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

Can someone help me?

+4
source share
2 answers

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

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

But I suggest you not use *_s functions: they are worse than explicitly named functions. They require the same checks and make you feel safe when you do not. I suggest you not use them because of the false sense of security and the fact that they are not available in many implementations, and your programs work only in a limited subset of the possible machines.

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 */ 

And your use of feof() is wrong.
fscanf() returns EOF when there is an error (end of file or match with error or read error ...).

You can use feof() to determine why fscanf() failed, and not to check if it fscanf() on the next call.

 /* 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 */; 
+9
source

If you think that the file (data.txt) exists, your application probably does not work with the current directory installed where the file is located. This will cause fopen_s () to crash.

0
source

All Articles