I/O流 文件读写

来源:互联网 发布:金纺的危害知乎 编辑:程序博客网 时间:2024/04/29 23:01


流:

“流”即是流动的意思,是物质从一处向另一处流动的过程。

C++流是指信息从外部输入设备(键盘等) 向计算机内部(如内存)输入和从内存向外部输出设备(显示器)输出的过程。这种输入输出的过程被形象的成为“流”

为了实现这种流动,C++定义了I/O标准库,这些每个类都成为流/流类,完成一些功能。

#define _CRT_SECURE_NO_WARNINGS 1


#include<iostream>
#include<stdlib.h>
#include<fstream>
using namespace std;


void WriteFile(const char *filename)
{
//1,打开文件
ofstream ofs(filename,ofstream::out);
//2,写入文件
string buf("hello");
ofs.write(buf.c_str(), buf.length());
ofs.put('w');
ofs.put('o');
ofs.put('r');
ofs.put('l');
ofs.put('d');
ofs.close();
}


void Readfile(const char *filename)
{
//1,打开文件
ifstream ifs(filename, ifstream::in);
//2,一个字符一个字符读取文件
char c;
cout << "get";
while (ifs.get(c))
cout << c;


cout << endl;
ifs.close();
//3,一行一行读取文件
char buf[256];
ifs.open(filename, ifstream::in);
ifs.seekg(ifs.beg);
ifs.getline(buf, 256);
cout << "GetLine:" << buf << endl;
ifs.getline(buf, 256);
cout << buf << endl;
}
int main()
{
system("pause");
return 0;
}

0 0
原创粉丝点击