关于文件读写的有关问题,哪位大侠帮忙看看,不胜感激~
关于文件读写的问题,哪位大侠帮忙看看,不胜感激~~~
想实现删除指定文件中的某一行的功能,思路是,先读取指定文件,如果读到指定行,就不存,否则存于另一个文件中,最后再将其重命名为指定文件。在传递DelLine为0时(其他的没有试呢。。)第一次运行是没问题的,但是我想再删除一次的时候,发现我的指定文件会变为空。这是哪里除了问题呢?
bool Deleteline(string DatPath,int DelLine)
{
fstream iofile(DatPath.c_str());
if(!iofile.is_open())
{
cout<<"open "<<DatPath<<" error!"<<endl;
return 0;
}
fstream Backup("E:\KeyBackup.dat", ios_base::in);// attempt open for read
if (!Backup)
{
// file doesn't exist; create a new one
Backup.open("E:\KeyBackup.dat", ios_base::out);
}
else //ok, file exists; close and reopen in write mode
{
Backup.close();
Backup.open("E:\KeyBackup.dat", ios_base::out); // reopen for write
}
if(!Backup.is_open())
{
cout<<"open E:\KeyBackup.dat error!"<<endl;
return 0;
}
int i =0;
string buf = "";
while( !iofile.eof())
{
getline(iofile,buf);
if (i != DelLine)
{
Backup << buf <<endl;
}
i++;
}
iofile.close();
Backup.close();
if(!remove(DatPath.c_str()))//删除成功
{
cout<<DatPath<<" 已成功删除."<<endl;
}
else
return false;
string BackupPath = "E:\KeyBackup.dat";
if(!rename(BackupPath.c_str(),DatPath.c_str()))//重命名
{
cout<<"E:\KeyBackup.dat 成功重命名为: "<<DatPath<<endl;
}
else
return false;
cout << "成功删除"<<DatPath<<"第"<< DelLine<<"行"<<endl;
return true;
}
------解决方案--------------------
fstream Backup("E:\KeyBackup.dat", ios_base::in);
代码没看 但感觉fstream Backup("E:\\KeyBackup.dat", ios_base::in);这样才是正确的吧
想实现删除指定文件中的某一行的功能,思路是,先读取指定文件,如果读到指定行,就不存,否则存于另一个文件中,最后再将其重命名为指定文件。在传递DelLine为0时(其他的没有试呢。。)第一次运行是没问题的,但是我想再删除一次的时候,发现我的指定文件会变为空。这是哪里除了问题呢?
bool Deleteline(string DatPath,int DelLine)
{
fstream iofile(DatPath.c_str());
if(!iofile.is_open())
{
cout<<"open "<<DatPath<<" error!"<<endl;
return 0;
}
fstream Backup("E:\KeyBackup.dat", ios_base::in);// attempt open for read
if (!Backup)
{
// file doesn't exist; create a new one
Backup.open("E:\KeyBackup.dat", ios_base::out);
}
else //ok, file exists; close and reopen in write mode
{
Backup.close();
Backup.open("E:\KeyBackup.dat", ios_base::out); // reopen for write
}
if(!Backup.is_open())
{
cout<<"open E:\KeyBackup.dat error!"<<endl;
return 0;
}
int i =0;
string buf = "";
while( !iofile.eof())
{
getline(iofile,buf);
if (i != DelLine)
{
Backup << buf <<endl;
}
i++;
}
iofile.close();
Backup.close();
if(!remove(DatPath.c_str()))//删除成功
{
cout<<DatPath<<" 已成功删除."<<endl;
}
else
return false;
string BackupPath = "E:\KeyBackup.dat";
if(!rename(BackupPath.c_str(),DatPath.c_str()))//重命名
{
cout<<"E:\KeyBackup.dat 成功重命名为: "<<DatPath<<endl;
}
else
return false;
cout << "成功删除"<<DatPath<<"第"<< DelLine<<"行"<<endl;
return true;
}
------解决方案--------------------
fstream Backup("E:\KeyBackup.dat", ios_base::in);
代码没看 但感觉fstream Backup("E:\\KeyBackup.dat", ios_base::in);这样才是正确的吧