gpt4 book ai didi

c - C/C++ 中文件读取的重命名文件的扩展问题

转载 作者:行者123 更新时间:2023-11-30 15:30:08 32 4
gpt4 key购买 nike

我有一个用于读取 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);

最佳答案

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

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

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

此外,您还应该检查 lCharIndx 是否在 sChar 的数组大小内。

关于c - C/C++ 中文件读取的重命名文件的扩展问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25782678/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com