我需要文本文件的最开始或者最后插入一行字符串,应该如何做?

解决方案 »

  1.   

    最后一行,可以在打开文件的时候指定 CFile::modeNoTruncate即可。
    在第一行,要把文件都读出来,然后重新写入。
      

  2.   

    TRY
    {
    CStdioFile f3( _T("c:\\test.txt"),
    CFile::modeNoTruncate | CFile::modeWrite | CFile::modeRead ); f3.Seek(0, CFile::begin);//定位到文件开头 f3.WriteString(_T("111111111\n"));
    f3.WriteString(_T("222222222\n"));
    f3.Seek(0, CFile::end);//定位到文件末尾
    f3.WriteString(_T("\nfffffffff\n"));
    f3.Close();
    }
    CATCH( CFileException, e )
    {
                //异常处理
    }
    END_CATCH
      

  3.   

    不废话,直接上代码
    char path[MAX_PATH];
    CString csDir;
    SYSTEMTIME st;
    CStdioFile cErrorlog;
    CFileException e;GetCurrentDirectory(MAX_PATH, path);BOOL CConnectDlg::WriteInFile(LPCSTR csPrint)
    {
    CString strDate, strTime;
    GetLocalTime(&st);
    strDate.Format("%02d月%02d日", st.wMonth, st.wDay);
    strTime.Format("%02d点", st.wHour);
    csDir.Format("%s",path);
    csDir = csDir + "\\ErrorLogFile_"+ m_UserName + "_" + strDate + strTime + ".txt";
    // printf("%s \n", csDir); CString csPrintContent;
    csPrintContent = csPrint;
    iLength = csPrintContent.GetLength();
    if(!cErrorlog.Open(csDir,CFile::modeCreate| CFile::modeNoTruncate|CFile::modeWrite|CFile::typeText|CStdioFile::shareDenyWrite))
    {
    CString str;
    str.Format(_T("%d"), e.m_cause);
    printf( "Can't create ErrorLogFile for %s! \n", str);
    return FALSE;
    }
    cErrorlog.Seek(0, CFile::end);
    cErrorlog.Write(csPrintContent, iLength);
    cErrorlog.Close();
    return TRUE;
    }
      

  4.   

    写入当前路径下,文件名字为ErrorLogFile_m_UserName_xx月xx日xx点.txt
    插入内容为csPrint,插入到文件最后部分。
      

  5.   

    输出内容如下:14时53分05秒Error: test2 login failed for disconnected from the network14时53分13秒Error: test2 login failed for disconnected from the network14时53分19秒Error: test2 login failed for disconnected from the network14时53分27秒Error: test2 login failed for disconnected from the network14时53分33秒Error: test2 login failed for disconnected from the network14时53分40秒Error: test2 login failed for disconnected from the network14时53分46秒Error: test2 login failed for disconnected from the network14时53分52秒Error: test2 login failed for disconnected from the network