【发布时间】: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