【问题标题】:Extension issue for renamed file for FIle Reading in C / C++C/C++ 文件读取重命名文件的扩展问题
【发布时间】:2014-11-05 02:54:26
【问题描述】:

我有一个读取csv 文件头的代码。首先我检查扩展是否为.csv。然后我读了文件。但问题是,如果我重命名任何其他文件,例如将.xml 文件或.docx 文件改名为.csv,然后尝试读取它,则此文件扩展名检查不起作用。然后它崩溃了。
但我想在这种情况下抛出一个适当的错误。任何人都可以帮忙吗?以下是相关代码sn-ps:

    // 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);

【问题讨论】:

    标签: c csv file-io error-handling wchar


    【解决方案1】:
    while(sChar[lCharIndx] = fgetwc(fpInpFile))
    

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

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

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

    【讨论】:

    • 是的。你是对的。我完全忘记了文件检查的结束。非常感谢您指出。关于 lCharIndx,这不是问题,因为检查 lHeaderLength >= 100 可确保 lCharIndx 始终在 sChar 的数组大小(即 100)内。但它没有解决我原来的问题,即编辑文件的扩展名。你能帮我解决这个问题吗?再次感谢。
    • @sudiptaasi 当你发现你不支持文件格式时应该识别并抛出错误
    猜你喜欢
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    相关资源
    最近更新 更多