【原】C++ 文件流的读取控制_C/C++_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > C/C++ > 【原】C++ 文件流的读取控制

【原】C++ 文件流的读取控制

 2011/9/16 8:11:47  pswzyu  http://pswzyu.iteye.com  我要评论(0)
  • 摘要:#include<iostream>#include<fstream>#include<exception>#include<string>intmain(){usingnamespacestd;fstreamf;try{f.open("a.txt",ios::binary|ios::in);//打开文件失败不会throw}catch(exceptionex){cout<<ex.what()<<endl;}cout<
  • 标签:文件 c++

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

int main()
{
? ? using namespace std;
? ? fstream f;
? ? try
? ? {
? ?? ???f.open("a.txt", ios::binary|ios::in); // 打开文件失败不会throw
? ? }catch (exception ex)
? ? {
? ?? ???cout << ex.what() << endl;
? ? }
? ? cout << f.is_open() << endl; // 打开文件成功与否要通过这个判断
? ? cout << f.tellg() << endl; // 当前指针, 如果打开文件失败, 这里是-1
? ? string file_content;
? ? int read_count = 0;
? ? while (!f.eof()) // 没到结尾
? ? {
? ?? ???
? ?? ???char buffer[11];
? ?? ???f.read(buffer, 10); // 读取文件
? ?? ???read_count = f.eofbit;
? ?? ???cout << f.gcount() << endl; // 实际读取的字节数
? ?? ???buffer[f.gcount()] = '\0';
? ?? ???cout << buffer << endl;
? ?? ???file_content += buffer;
? ? }
? ? cout << file_content << endl;
? ? getchar();
? ? return 0;
}

?

--------------------EOF---------------------

发表评论
用户名: 匿名