C++文件流操作的问题

xuefey 2008-10-19 08:25:55
我写了一小段代码,想试验利用文件流复制文件内容的功能。但非常奇怪的是,复制得到的文件,最后的一个字符会重复多一个字符。例如:原文件内容是“abcd",复制到新文件后,内容变成了“abcdd”,请各位高手帮忙看看是什么原因,代码如下:


#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream ifile;
ofstream ofile;
char ch;
ifile.open("TEST.txt");
if(!ifile){
cout<<"没有找到指定的文件"<<endl;
return 0;
}
ofile.open("TEST1.txt");
if(!ofile){
cout<<"无法建立以TEST1.txt命名的文件";
return 0;
}
while(true){
ifile>>ch;
cout<<ch;
ofile<<ch;
if(ifile.eof()) {
ifile.close();
ofile.close();
return 0;
}
}
}
...全文
179 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
闪亮新星 2008-12-18
  • 打赏
  • 举报
回复
怎么没有
file.close
giant1st 2008-10-19
  • 打赏
  • 举报
回复
说句废话: >> 有 驻留 功能,最后的字符 在被新的 对象更新前,仍然存在
xuefey 2008-10-19
  • 打赏
  • 举报
回复
感谢1楼的回答,我明白了,eof()是要到文件最后一个字符的后面才返回真,而不是最后一个字符,关键点在这里。呵呵。
appleshao 2008-10-19
  • 打赏
  • 举报
回复
我看走眼了return 0````{}没看清楚不好意思```
appleshao 2008-10-19
  • 打赏
  • 举报
回复
楼主啊问你一个问题,你帮我理解一下while(true)程序没有死掉么?
lzr4304061988012 2008-10-19
  • 打赏
  • 举报
回复

#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream ifile;
ofstream ofile;
char ch;
ifile.open("TEST.txt");
if(!ifile){
cout<<"没有找到指定的文件"<<endl;
return 0;
}
ofile.open("TEST1.txt");
if(!ofile){
cout<<"无法建立以TEST1.txt命名的文件";
return 0;
}
while(true){
ifile>>ch;
if(ifile.eof()) //注意这个函数,是读到文件结尾时,返回真.
{
ifile.close();
ofile.close();
return 0;}
cout<<ch;
ofile<<ch;


}
}

lzr4304061988012 2008-10-19
  • 打赏
  • 举报
回复


#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream ifile;
ofstream ofile;
char ch;
ifile.open("1.txt");
if(!ifile){
cout<<"没有找到指定的文件"<<endl;
return 0;
}
ofile.open("file1.txt");
if(!ofile){
cout<<"无法建立以TEST1.txt命名的文件";
return 0;
}
while(true){
ifile>>ch;
if(ifile.eof()) {
ifile.close();
ofile.close();
return 0;}
cout<<ch;
ofile<<ch;


}
}

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧