关闭fstream,可以在代码中进一步编辑文件

时间:2014-06-30 19:37:15

标签: c++ fstream ifstream ofstream

我试图打开并读取文件,复制它的内容,同时将其修改为另一个文件,删除原始文件并将临时文件重命名为原始名称。删除和重命名会给出权限被拒绝错误,因为我不知道在继续使用代码之前如何关闭文件,请帮助。

#include <iostream>
#include <fstream>
#include <stdio.h>

using namespace std;

int main()
{
    string strReplace = "5";
    string strNew = "4";
    ifstream filein("C:/test.txt"); //File to read from
    ofstream fileout("C:/test1.txt"); //Temporary file
    if(!filein || !fileout)
    {
        cout << "Error opening files!" << endl;
        return 1;
    }

    string strTemp;
    //bool found = false;
    while(filein >> strTemp)
    {
        if(strTemp == strReplace){
            strTemp = strNew;
            //found = true;
        }
        strTemp += "\n";
        fileout << strTemp;
        //if(found) break;
    }



    //remove original file
    if( remove( "C:/test.txt" ) != 0 )
    perror( "Error deleting file" );
    else
    puts( "File successfully deleted" );

    //rename temp file to original file
    char oldname[] ="C:/test1.txt";
    char newname[] ="C:/test.txt";

    int result= rename( oldname , newname );
    if ( result == 0 )
    puts ( "File successfully renamed" );
    else
    perror( "Error renaming file" );

    return 0;
}

1 个答案:

答案 0 :(得分:2)

只需filein.close()fileout.close()。参考here