c++ファイル操作
1648 ワード
c++ファイル操作はライブラリ「fstream」を使用して解決できます
重要なクラスが3つあります.
ifstreamは、ファイル読み取り用のストリームofstreamであり、ファイル書き込み用のストリームfstreamは、ファイル読み取りおよび書き込み用のストリームである
ファイルを開く
Openには2つのパラメータがあり、最初のパラメータは開くファイルのアドレスを表します.2番目のパラメータは、操作ファイルのモードを表します.(以下、具体的に示す)
モードフラグ
説明
ios::app
追加モードでは、すべての書き込みデータがファイルの末尾に追加されます
ios::ate
ファイルを開くと、ファイルの最後に定義されます.
ios::in
読み込み用にファイルを開く
ios::out
ファイルを開いて書き込みを行います(ファイルが存在する場合は、クリアする前にすべての内容をクリアします).
ios::trunc
このファイルが存在する場合、その内容はファイルを開く前に遮断され、すなわちファイル長を0にする.(元のファイルの内容を削除し、存在しない場合はファイルを作成しません)
例
例1:(ドキュメントを読み取り、動作ごとに1つずつコンテナに保存し、反復器で出力)
例2:
重要なクラスが3つあります.
ifstream
ofstream
fstream
ifstreamは、ファイル読み取り用のストリームofstreamであり、ファイル書き込み用のストリームfstreamは、ファイル読み取りおよび書き込み用のストリームである
ファイルを開く
void open(const std::string& __s, ios_base::openmode __mode );
Openには2つのパラメータがあり、最初のパラメータは開くファイルのアドレスを表します.2番目のパラメータは、操作ファイルのモードを表します.(以下、具体的に示す)
モードフラグ
説明
ios::app
追加モードでは、すべての書き込みデータがファイルの末尾に追加されます
ios::ate
ファイルを開くと、ファイルの最後に定義されます.
ios::in
読み込み用にファイルを開く
ios::out
ファイルを開いて書き込みを行います(ファイルが存在する場合は、クリアする前にすべての内容をクリアします).
ios::trunc
このファイルが存在する場合、その内容はファイルを開く前に遮断され、すなわちファイル長を0にする.(元のファイルの内容を削除し、存在しない場合はファイルを作成しません)
例
例1:(ドキュメントを読み取り、動作ごとに1つずつコンテナに保存し、反復器で出力)
#include
#include
#include
#include
using namespace std;
int main(void)
{
ifstream in("data");//
if (!in)
{
cerr << " !" << endl;
return -1;
}
string line;
vector words;
while (getline(in, line))//
{
words.push_back(line);// vector
}
in.close();// ,
vector::const_iterator it = words.begin();//
while (it != words.end()) // vector
{
cout << *it << endl;
++it;
}
//return 0;
system("pause");
}
例2:
#include
#include
using namespace std;
int main()
{
fstream fd;
fd.open("123.txt",ios::app);
fd<>s;
cout<