C++fstream/ifstream/ofstreamクラスファイル操作用


一、ofstream//ファイルストリームを出力し、ファイルに内容を書く
#include
#include 
using namespace std;
int main() 
{
	ofstream file1("ofstream.txt");
	file1 << "hello world";
	file1.close();
}

二、ifstream//ファイルフローを入力し、既存のファイルから読む
#include
#include 
using namespace std;
int main() 
{
	char ch;
	ifstream file1("ofstream.txt");
	while (file1.get(ch))
	{
		cout << ch;
	}
	file1.close();
}

三、fstream//ファイルストリーム、ファイルを開いて読み書きする
オープンモード:ios::app追加用にファイルを開き、存在しない場合は作成し、存在しない場合はファイルの末尾に空欄で書き込み、ファイルヘッダios::ateオープン時にファイルの末尾に定義するios::binaryはバイナリモードで読み書きios::inは読み取り権限でファイルを開き、存在しない場合は失敗します.不明なiosが存在します::outは書き込み権限でファイルを開き、存在しない場合は作成し、存在する場合はiosをクリアします::truncはファイルを開くときはクリアします
コンストラクション関数またはメンバー関数openファイルgoodメンバー関数を開くには、ストリームがeofメンバー関数で入力ストリームが終了するかどうかを確認します(ファイルが読み取り終了するかどうかを検出します)
 
>>オペレータは、ファイルから変数にデータを読み込むために使用します<
file>>char *;
file>>char;
file.get(char);
file.get(char *,int);
file.getline(char *,int sz);
 file.getline(char *,int sz,char eol);
#include 
#include 
using namespace std;

int main()
{
	fstream fs;
	fs.open("test1.txt",ios::out);
	if(fs.good())
	{
		cout << "      " << endl;
	}
	else
	{
		cout << "      " << endl;
	}
	int i=9;
	while(i--)
	{
		fs << "hello" << " " << 100 << endl;
	}
}
#include 
#include 

using namespace std;

int main()
{
	fstream fs("test1.txt",ios::in);
	if(fs.good())
	{
		cout << "      " << endl;
	}
	else
	{
		cout << "      " << endl;
	}
    //   
    string str;
	int num;
	fs >> str;
	fs >> num;
	cout << str << "--" << num << endl;
    //   
	char ch;
	while((ch=fs.get())!=EOF)
	{
		cout<

コントロール関数の書式設定は、左揃え、右揃え、幅、塗りつぶし、小数点以下の桁数などです.
バイナリ読み書き:メンバー関数read/write read(char_type*_s,streamsize__n)gcountメンバー関数は、前回ストリームのバイナリ読み書き操作のバイト数を取得できます.
write(char_type*_s,streamsize_n)goodメンバー関数は、書き込み操作が成功したかどうかを取得できます.
バイナリ読み書きで書かれたレプリケーション・ファイルの操作:
#include
#include
using namespace std;
int main()
{
	ifstream fin("test.txt", ios::in|ios::binary);
	if (!fin)
	{
		cout << "File open error!
"; return -1; } ofstream fout("test2.txt", ios::binary); char c[1024]; while (!fin.eof()) { fin.read(c, 1024); fout.write(c, fin.gcount()); } fin.close(); fout.close(); }

ランダム読み書き:seekp(off_type,ios_base::seekdir)機能:ファイルの位置ポインタoff_を設定するtype:オフセット値正の値を右に、負の値を左にseekdir:ベース位置ios::begファイル先頭ios::curファイル現在位置ios::endファイル末尾
ファイル位置ポインタの取得:tellpこのメンバー関数は、現在のファイルストリームの位置ポインタ(バイト数)を返します.この関数を使用してファイルのサイズを取得することもできます.
 //             
    fs.seekp(0,ios::end);
    cout << "       :" << fs.tellp() << endl;