Difference in fscanf / fscanf_s behavior

I am puzzled by the following difference in behavior:

// suppose myfile.txt contains a single line with the single character 's' errno_t res; FILE* fp; char cmd[81]; res = fopen_s(&fp, "D:\\myfile.txt", "rb" ); fscanf(fp,"%80s",cmd); // cmd now contains 's/0' fclose(fp); res = fopen_s(&fp, "D:\\myfile.txt", "rb" ); fscanf_s(fp,"%80s",cmd); // cmd now contains '/0' ! fclose(fp); 

The results do not depend on the order of the call (i.e. first call fscanf_s, first you will get an empty string). Compiled on VC ++ - VS2005. Can anyone reproduce? Can someone explain?

Thanks!

+7
c ++ visual-c ++ crt visual-studio-2005
source share
3 answers

In the docs on fscanf_s() , http://msdn.microsoft.com/en-us/library/6ybhk9kc.aspx :

The main difference between protected functions (with suffix _s) and older functions is that protected functions require the size of each of the fields c, C, s, S and [type, passed as an argument immediately after the variable. See Scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l, and scanf Width Specification for more information.

And http://msdn.microsoft.com/en-us/library/w40768et.aspx :

Unlike scanf and wscanf, scanf_s and wscanf_s require a buffer size for all input parameters like c, C, s, S or [. The size of the buffer is passed as an additional parameter immediately after the pointer to the buffer or variable. For example, when reading a row, the buffer size for this row is passed as follows:

char s [10];

scanf ("% 9s", s, 10);

So you should call it like this:

 fscanf_s(fp,"%80s",cmd, sizeof(cmd)); 
+8
source share

fscanf_s (and the whole scanf_s family) requires you to pass the size of any %c , %c , %s , %s or %[ after the buffer itself; you omit this argument:

 fscanf_s(fp, "%80s", cmd, 81); 
+6
source share

C ++ is marked in your question, and you compile in VC ++, but using fscanf? Get std :: ifstream.

 std::string buffer; std::ifstream fp("my filepath"); fp >> buffer; 
+2
source share

All Articles