C++ でファイルを作成する
- 
          
            C++ で std::fstream、std::open、std::ios_base::outを使用してファイルを作成する
- 
          
            C++ で std::fstream、std::open、std::ios_base::appを使用してファイルを作成する
- 
          
            C++ で std::fstreamおよびfopen関数を使用してファイルを作成する
 
この記事では、C++ でファイルを作成する方法のいくつかの方法について説明します。
C++ で std::fstream、std::open、std::ios_base::out を使用してファイルを作成する
    
ファイルの作成は通常、ファイルを開く操作に関連しています。ファイルを開く操作自体は、ファイルストリーム構造をディスク上の対応する物理ファイルに関連付けるアクションです。通常、ファイルの作成操作は、プログラムがファイルを開くモードによって異なります。ファイルを開くには、書き込み専用モード、読み取り専用モード、追加モードなど、複数のモードがあります。通常、ファイルへの書き込みを伴うすべてのモードは、指定されたファイル名が存在しない場合に新しいファイルを作成することを目的としています。したがって、std::fstream の open 組み込み関数を呼び出して、最初の string 引数として指定された名前で新しいファイルを作成する必要があります。open の 2 番目の引数は、ファイルストリームを開くモードを指定し、これらのモードは言語によって事前定義されています(ページを参照してください)。
#include <fstream>
#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
using std::fstream;
using std::ofstream;
using std::string;
int main() {
  string filename("output.txt");
  fstream output_fstream;
  output_fstream.open(filename, std::ios_base::out);
  if (!output_fstream.is_open()) {
    cerr << "Failed to open " << filename << '\n';
  } else {
    output_fstream << "Maecenas accumsan purus id \norci gravida pellentesque."
                   << endl;
    cerr << "Done Writing!" << endl;
  }
  return EXIT_SUCCESS;
}
出力:
Done Writing!
C++ で std::fstream、std::open、std::ios_base::app を使用してファイルを作成する
または、std::ios_base::app で示される追加モードでファイルを開き、書き込みのたびにストリームをファイルの最後に強制的に配置することもできます。このモードでは、指定されたパスに新しいファイルが存在しない場合にも、新しいファイルが作成されることを前提としています。正常に開かれたファイルストリームは、ストリームが関連付けられたときに true を返す is_open 関数で確認できることに注意してください。
#include <fstream>
#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
using std::fstream;
using std::ofstream;
using std::string;
int main() {
  string text("Large text stored as a string\n");
  string filename2("output2.txt");
  fstream outfile;
  outfile.open(filename2, std::ios_base::app);
  if (!outfile.is_open()) {
    cerr << "failed to open " << filename2 << '\n';
  } else {
    outfile.write(text.data(), text.size());
    cerr << "Done Writing!" << endl;
  }
  return EXIT_SUCCESS;
}
出力:
Done Writing!
C++ で std::fstream および fopen 関数を使用してファイルを作成する
ファイルを作成する別のオプションは、FILE*構造を返す C 標準ライブラリインターフェイス fopen を利用することです。この関数は 2つの引数を取ります。開くファイルのパス名を指定する文字列と、開くモードを示す別の文字列リテラルです。6つの一般的なモードが定義されています:r-ストリームが最初に配置されている場合は読み取り専用、w-書き込み専用-最初に、a-書き込み専用(追加)-最後に配置ファイル、および 3つのプラスバージョン-r+、w+、a+、さらに反対のモードが含まれています。
#include <fstream>
#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
using std::fstream;
using std::ofstream;
using std::string;
int main() {
  string text("Large text stored as a string\n");
  fstream outfile;
  string filename3("output3.txt");
  FILE *o_file = fopen(filename3.c_str(), "w+");
  if (o_file) {
    fwrite(text.c_str(), 1, text.size(), o_file);
    cerr << "Done Writing!" << endl;
  }
  return EXIT_SUCCESS;
}
出力:
Done Writing!
