【问题标题】:Closing fstream so files can be edited further in the code关闭 fstream 以便可以在代码中进一步编辑文件
【发布时间】:2014-06-30 19:37:15
【问题描述】:

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

#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;
}

【问题讨论】:

  • 您是否尝试过在流对象上使用close...?
  • 将您的代码拆分为单独的函数,每个函数都做一件事,并且您不会遇到这个问题,因为 std 流在超出范围时会关闭。再加上专用功能的所有其他好处
  • 谢谢你的建议,我会照做的

标签: c++ fstream ifstream ofstream


【解决方案1】:

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

【讨论】:

  • ermagerd 谢谢,不敢相信它这么简单,我已经搜索过但在复杂的例子中迷失了
猜你喜欢
  • 2020-08-15
  • 2015-11-20
  • 2021-05-10
  • 1970-01-01
  • 2020-03-17
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多