在vc ++中删除文件的元素

时间:2017-06-05 09:24:00

标签: visual-c++ mfc

CStringArray myArray;
myArray.copy(copiedsomeelements);
CString file1="myfile1";
CString file2="myfile2";
FILE *fp1,*fp2;
CString linetocompare="mytext";
fp1 = fopen(myfile1, "rb");
fread(data, 1280, 1, fp1);
fclose(fp1);
TCHAR * pch = _tcstok(data, _T("\r\n"));


fp2 = fopen(myfile2, "w"); //open new file

for (int m = 0; m < myArray.GetCount(); m++)
{
        CString temp(pch);
        if (strcmp(myArray.GetAt(m), linetocompare) != NULL)
        {
                fprintf(fp2, "%s", temp); 
                fwrite("\r\n", 1, 1, fp2);
        }
        pch = _tcstok(NULL, _T("\r\n"));
}
fclose(fp2);
remove(myfile1); //remove old file
rename(myfile2, myfile1);

上面的代码对我来说很好,但不是所有的时间。有时会写出&#34; myfile2&#34;因为没有比较&#34; linetocomapare&#34;元件。 请帮我解决一下这个。 如果需要澄清,请与我们联系。谢谢。

1 个答案:

答案 0 :(得分:1)

MFC有一个CStdioFile类,它包含了一些文件,可以处理换行符。这里有一些用于加载/保存文本文件的便利功能:

void ReadTextFileContents(CString const& filePath,
    CArray<CString>& lines,
    UINT openFlags = CFile::modeRead | CFile::shareDenyWrite)
{
    CStdioFile file(filePath, openFlags);

    try
    {
        CString line;
        while (file.ReadString(line))
            lines.Add(line);
        file.Close();
    }
    catch (...)
    {
        file.Abort();
        throw;
    }
}

void WriteTextFileContents(CString const& filePath,
    CArray<CString> const& lines,
    UINT openFlags = CFile::modeCreate | CFile::modeWrite |
    CFile::shareExclusive)
{
    CStdioFile file(filePath, openFlags);

    try
    {
        for (INT_PTR i = 0, count = lines.GetCount(); i < count; ++i)
        {
            file.WriteString(lines[i]);
            if (i < (count - 1))
            {
                // NOTE: The default mode for CStdioFile is text mode
                // MSDN: Text mode provides special processing for carriage
                // return-linefeed pairs. When you write a newline character
                // (0x0A) to a text-mode CStdioFile object, the byte pair
                // (0x0D, 0x0A) is sent to the file. When you read, the
                // byte pair (0x0D, 0x0A) is translated to a single 0x0A
                // byte.
                file.WriteString(_T("\n"));
            }
        }
        file.Close();
    }
    catch (...)
    {
        file.Abort();
        throw;
    }
}

现在你可以这样做:

    try
    {
        CArray<CString> lines;
        ReadTextFileContents(fileName, lines);

        // Do what you want with lines, remove items, copy to
        // another array, etc.

        // Now write them somewhere
        WriteTextFileContents(fileName2, lines);
    }
    catch (CException* ex)
    {
        // Grab and display error message here
        //ex->GetErrorMessage();

        ex->Delete();
    }
相关问题