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

【原】C++ 资料流的读取控制

2012-10-10 
【原】C++ 文件流的读取控制#include iostream#include fstream#include exception#include stringi

【原】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---------------------

热点排行