0

When we use fscanf_s method in Visual studio 2013 (C++ Console application), Os- Winsever2008 (64 bit), the file pointer reads the data one or 2 bytes in advance. Eg: While reading text file , the second line of the file is "Administartor", but the fscanf_s() returns the word as "dministrator". Please help me to correct this issue. The code is working fine with WIndows XP 32 bit using Visual studio 2008.

FILE* pFile;
pFile = NULL;
string strFile = "E:\\10_Products.lrf";
fopen_s(&pFile, strFile.c_str(), "r");
char szTemp[256];
string strTemp = "";
if (NULL != pFile)
{   
    while (!feof(pFile))
    {
        nRet = fscanf_s(pFile, "%s", szTemp);
        if (EOF == nRet)
        {
            cout << "EOF detected";
        }
    }
    return 0;
}

The format of 10_Products.lrf file is given below.

[OPERATOR_LEVEL]
Administrator
chiwangc
  • 3,566
  • 16
  • 26
  • 32
  • sample code FILE* pFile; pFile = NULL; string strFile = "E:\\10_Products.lrf"; fopen_s(&pFile, strFile.c_str(), "r"); char szTemp[256]; string strTemp = ""; if (NULL != pFile) { while (!feof(pFile)) { nRet = fscanf_s(pFile, "%s", szTemp); if (EOF == nRet) { cout << "EOF detected"; } } return 0; } – Monisha M J Apr 24 '15 at 08:00
  • You should edit your post instead of adding this as comment – Anton Savin Apr 24 '15 at 08:04
  • [`while(!feof())` is always wrong](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – Ken Y-N Apr 24 '15 at 08:13
  • If use fscanf this code works properly. – Monisha M J Apr 24 '15 at 08:39
  • For fscanf_s it shows this issue, pls help to find the issue – Monisha M J Apr 24 '15 at 09:28

1 Answers1

0

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

The main difference between the secure functions (with the _s suffix) and the older functions is that the secure functions require the size of each c, C, s, S and [ type field to be passed as an argument immediately following the variable. For more information, see scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l and scanf Width Specification.

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

Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or [. The buffer size is passed as an additional parameter immediately following the pointer to the buffer or variable. For example, if reading a string, the buffer size for that string is passed as follows:

char s[10];

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

So you should call it like so:

fscanf_s(fp,"%80s",cmd, sizeof(cmd));

CreativeMind
  • 897
  • 6
  • 19