0

I have a code for reading the header of a csv file. First I check whether the extenson is .csv or not. Then I read the file. But the problem is, if I rename any other file, say a .xml file or a .docx file to .csv and then try to read it, then this file extension check doesn't work. It then crashes.
But I want to throw a proper error in such cases. Can anyone help? Here are the relevant code snippets:

    // Extracting the extension of the file. Since only csv files are allowed, 
    // for rest of the extensions, appropriate error is being thrown

    sExt = wcsrchr(sFile, L'.');

    if(wcscmp(sExt, L".csv") != 0)
    {
        return -1;
    } 

    _wfopen_s(&fpInpFile, sFile, L"rt");

    if(fpInpFile == NULL)
    {
        return -1;
    } 

    while(sChar[lCharIndx] = fgetwc(fpInpFile))
    {
        lVarLength ++;
        lHeaderLength ++;

       // If Variable name is too long, or if the length of the header is too long, throw an error
        if(lVarLength >= 100 || lHeaderLength >= 100)
        {                   
            fclose(fpInpFile);
            return -1;
        }

        // Resetting varibale length before reading length of next variable
        if(sChar[lCharIndx] == ',')
            lVarLength = 0;

        // Header reading is done, so exiting the loop
        if(sChar[lCharIndx] == '\n')
            break;

        lCharIndx ++;
    }

    fclose(fpInpFile);
4

1 回答 1

1
while(sChar[lCharIndx] = fgetwc(fpInpFile))

您不应该以这种方式检查文件结尾。反而:

wint_t wch;
while ((wch = fgetwc(fpInpFile)) != WEOF)
{
    sChar[lCharIndx] = wch;

此外,您应该检查是否lCharIndx在数组大小范围内sChar

于 2014-09-11T08:35:05.190 回答