64,701
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
fstream ftm("c:\\test.txt",fstream::in|fstream::out);
if(!ftm){
cout<<"异常"<<endl;
return -1;
}
string line,lastline;
bool hasLine=false;
while(getline(ftm,line)){
hasLine=true;
lastline=line;
}
if(!hasLine){
ftm<<"hello10"<<endl;
cout<<"最多可使用10次"<<endl;
}else{
cout<<lastline<<endl;
} ftm.close();
return 0;
}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
fstream ftm;
ftm.open("d:\\test.txt",ios::in|ios::out|ios::app);
if(!ftm){
cout<<"异常"<<endl;
return -1;
}
string line,lastline;
int cnt=1; ////////////add
while((getline(ftm,line))&&(cnt<=2)){ /////////////add
cnt++; ////////////add
lastline=line;
}
//判断一下是否有效,无效则clear下
if (ftm.eof())
{
ftm.clear();
}
ftm.seekp(ios::end);//让流指向文件最后
ftm<<"hello"<<endl;
ftm.flush();
ftm.close();
return 0;
}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
fstream ftm;
ftm.open("d:\\test.txt",ios::in|ios::out|ios::app);
if(!ftm){
cout<<"异常"<<endl;
return -1;
}
string line,lastline;
int cnt=1; ////////////add
while((getline(ftm,line))&&(cnt<=2)){ /////////////add
cnt++; ////////////add
lastline=line;
}
ftm.seekp(ios::end);//让流指向文件最后
ftm<<"hello"<<endl;
ftm.flush();
ftm.close();
return 0;
}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
fstream ftm("c:\\test.txt",fstream::in);
if(!ftm){
cout<<"异常"<<endl;
return -1;
}
string line,lastline;
bool hasLine=false;
while(getline(ftm,line)){
hasLine=true;
lastline=line;
}
if(!hasLine){
ftm.close();
fstream ftm2("c:\\test.txt",fstream::out);
ftm2<<"hello10"<<endl;
cout<<"最多可使用10次"<<endl;
}else{
cout<<lastline<<endl;
} ftm.close();
return 0;
}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
fstream ftm;
ftm.open("d:\\test.txt",ios::in|ios::out|ios::app);
if(!ftm){
cout<<"异常"<<endl;
return -1;
}
string line,lastline;
int cnt=1; ////////////add
while((getline(ftm,line))&&(cnt<=2)){ /////////////add
cnt++; ////////////add
lastline=line;
}
//这时候文件流到达eof , clear()让文件流恢复有效状态
//ftm.clear(); ////////////del
ftm<<"hello"<<endl;
ftm.flush();
ftm.close();
return 0;
}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
fstream ftm;
ftm.open("d:\\test.txt",ios::in|ios::out|ios::app);
if(!ftm){
cout<<"异常"<<endl;
return -1;
}
string line,lastline;
while(getline(ftm,line)){
lastline=line;
}
//这时候文件流到达eof , clear()让文件流恢复有效状态
ftm.clear();
ftm<<"hello"<<endl;
ftm.flush();
ftm.close();
return 0;
}
int main(){
fstream ftm("c:\\test.txt",fstream::in|fstream::out);
ofstream f1("c:\\test.txt"); //++++ 这里
if(!ftm){
cout<<"异常"<<endl;
return -1;
}
string line,lastline;
bool hasLine=false;
while(getline(ftm,line)){
hasLine=true;
lastline=line;
}
if(!hasLine){
f1<<"hello10"<<endl;//++++ 这里
cout<<"最多可使用10次"<<endl;
}else{
cout<<lastline<<endl;
} ftm.close();
return 0;
}