1.fstream.STL

来源:互联网 发布:淘宝男鞋品牌排行榜 编辑:程序博客网 时间:2024/06/05 23:52

1.回车

STL里有个fstream类,用来读写文件,对于文本文件的回车处理得注意个问题,那就是开方模式中要使用ios_base::binary,才能正确的进行读写。读出数据时要有启用这个模式,写的时候也一样。 

  1. const char* filename="a.txt";
  2. fstream file;
  3. file.open(filename, ios_base::in | ios_base::binary);
  4. if (file.fail()) goto LB_FAIL;//失败
  5. //do something with file
  6. file.flush();
  7. file.close();
  8. //-----------------------------------
  9. file.clear(); //清除对象中保留的状态
  10. file.open(filename, ios_base::out | ios_base::binary);
  11. //do something with file
  12. file.flush();
  13. file.close();
  14. file.clear;
  15. LB_FAIL: return FALSE;

 

2.长度

文件长度可用来获取。目前没有办法缩短文件,如果改写后数据长度比原来的小,那么用ios_base::trunc清空内容再重新写入新数据。注:超笨!!!

  1. #include <fstream>
  2. const char* filename="a.txt";
  3. fstream file;
  4. file.open("a.txt", ios_base::in | ios_base::binary);
  5. file.seekg(0, fstream::end);
  6. cout << "file size: " << file.tellg() << std::endl;
原创粉丝点击