Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 关闭fstream以便可以在代码中进一步编辑文件_C++_Fstream_Ifstream_Ofstream - Fatal编程技术网

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

C++ 关闭fstream以便可以在代码中进一步编辑文件,c++,fstream,ifstream,ofstream,C++,Fstream,Ifstream,Ofstream,我试图打开并读取一个文件,将其内容复制到另一个文件,删除原始文件并将临时文件重命名为原始名称。删除和重命名导致权限被拒绝错误,因为我不知道如何在继续使用代码之前关闭文件,请帮助 #include <iostream> #include <fstream> #include <stdio.h> using namespace std; int main() { string strReplace = "5"; string strNew =

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

#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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串strReplace=“5”;
字符串strNew=“4”;
ifstream filein(“C:/test.txt”);//要从中读取的文件
ofstream文件输出(“C:/test1.txt”);//临时文件
如果(!filein | |!fileout)
{
cout strTemp)
{
如果(strTemp==strReplace){
strTemp=strNew;
//发现=真;
}
strTemp+=“\n”;

fileout简单地
filein.close()
fileout.close()
.Reference.

您是否尝试过在流对象上使用
close
?将代码拆分为不同的函数,每个函数只做一件事,这样您就不会有这个问题,因为std流在超出范围时会关闭。这加上专用函数的所有其他好处谢谢您的建议,我将遵循itermagerd thanks,真不敢相信这么简单,我已经搜索过了,但是在复杂的例子中迷失了方向