首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

求教关于fstream的seek和ate,app

2013-03-25 
求教关于fstream的seek跟ate,app本帖最后由 IMCNS 于 2013-03-18 14:11:26 编辑#include iostream#inclu

求教关于fstream的seek跟ate,app
本帖最后由 IMCNS 于 2013-03-18 14:11:26 编辑


#include <iostream>
#include <string>
#include <fstream>

int main()
{
//操作文件是ex12.txt
std::fstream file("ex12.txt",std::fstream::ate|std::fstream::out|std::fstream::in);
if(!file){ 
std::cerr<<"could not open the file"<<std::endl;
throw std::runtime_error("could not open the file");
}

file<<"123 321 1234567"<<std::endl;
std::string sentences;

//这里把文件标号定位到末尾了,为什么while循环还可以执行?
file.seekg(std::fstream::end);
while (getline(file,sentences)){
std::fstream::pos_type mark=file.tellg();

//这里我也把文件标号定位到末尾了,然后执行输入sentence.size(),但结果文件里
                  //却显示1213 21 1234567,与我预期的123 321 1234567 "换行" 13 大相庭径,
                  //why?
file.seekp(std::fstream::end);
file<<sentences.size()<<" ";
file.seekg(mark);
}
file.close();

system ("pause");
return 0;
}



除了以上代码注释的疑问之外,我还把文件模式由ate改为app,输出的结果就是我预期的结果了,

为什么我把文件标号定位到文件末尾了,while循环还会执行?而且我把文件标号定位到末尾之后进行输入,输入的信息却不是出现在文件的末尾,反而是文件开头再移2位...?

请知道的前辈详细解疑一下我的问题,在下感激不尽...
[解决办法]
//ios::app // 从后面添加
//ios::ate // 打开并找到文件尾


//操作文件是ex12.txt    
std::fstream file("ex12.txt",std::fstream::ate
[解决办法]
std::fstream::out
[解决办法]
std::fstream::in);    
if(!file)
{         
std::cerr<<"could not open the file"<<std::endl;        
throw std::runtime_error("could not open the file");    
}     
file<<"123 321 1234567"<<std::endl;    //hd: 输到文件, 1213321 1234567
std::string sentences;     
//这里把文件标号定位到末尾了,为什么while循环还可以执行?    
file.seekg(std::fstream::end);    //hd: 把光标定位到2的位置,而不是末尾
while (getline(file,sentences))   //hd: sentences为, 3 321 1234567
{        
std::fstream::pos_type mark=file.tellg();         //这里我也把文件标号定位到末尾了,然后执行输入sentence.size(),但结果文件里              //却显示1213 21 1234567,与我预期的123 321 1234567 "换行" 13 大相庭径,                  //why?        
file.seekp(std::fstream::end);      //hd: 重新把光标定位到2的位置  
file<<sentences.size()<<" ";        //hd: sentences.size()为13,输出字符串大小1,3,空格 也就变成了1213 21 1234567
file.seekg(mark);                   //hd: mark为17, 把光标移到末尾, 结束输出


}    
file.close();     
system ("pause");

return 0;
}

 

热点排行
Bad Request.