我有一个用于读取csv
文件标头的代码。首先,我检查范围是否为.csv
。然后我读了这个文件。但问题是,如果我重命名任何其他文件,将.xml
文件或.docx
文件说成.csv
,然后尝试阅读,那么此文件扩展名检查不会。工作。然后崩溃。
但是我希望在这种情况下抛出适当的错误。有人可以帮忙吗?以下是相关的代码段:
// 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);
答案 0 :(得分:1)
while(sChar[lCharIndx] = fgetwc(fpInpFile))
您不应该以这种方式检查文件结尾。代替:
wint_t wch;
while ((wch = fgetwc(fpInpFile)) != WEOF)
{
sChar[lCharIndx] = wch;
此外,您应该检查lCharIndx
是否在数组大小sChar
之内。