1. 程式人生 > >I/O流 檔案讀寫

I/O流 檔案讀寫

流:

“流”即是流動的意思,是物質從一處向另一處流動的過程。

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;
}