C++ファイルの読み書き


文書ディレクトリ
  • 1ファイルオープン方式
  • 2テキストファイルの読み書き
  • 3バイナリファイルの読み書き
  • 1ファイルの開き方
      
    開く
    用途
    ios::in
    ファイルを読む
    ios::out
    ファイルを書く
    ios::ate
    初期位置しょきいち:ファイルの最後
    ios::app
    追加
    ios::trunc
    ファイルが存在する場合は削除してから作成します
    ios::binary
    バイナリ方式
      ファイルの開き方は組み合わせて使用できます.「|」間隔:  例えばバイナリ方式でファイルを書きます:ios::binary|ios::out
    2テキストファイルの読み書き
    #include
    #include
    #include
    
    
    void output_test(std::string);
    void input_test(std::string);
    
    
    int main()
    {
         
    	std::string file_name = "test.txt";
    	output_test(file_name);
    	input_test(file_name);
    }
    
    
    void output_test(std::string file_name) {
         
    	std::ofstream ofs;
    	ofs.open(file_name, std::ios::out);
    	for (int i = 0; i < 5; i++)
    	{
         
    		ofs << " " << i << " 
    "
    ; } ofs.close(); } void input_test(std::string file_name) { std::ifstream ifs; ifs.open(file_name, std::ios::in); if (ifs.is_open()) { // /* char buf[104] = { 0 }; while (ifs >> buf) { std::cout << buf << std::endl; } */ // /* char buf[104] = { 0 }; while (ifs.getline(buf, sizeof(buf))) { std::cout << buf << std::endl; } */ // std::string buf; while (getline(ifs, buf)) { std::cout << buf << std::endl; } } ifs.close(); }

    3バイナリファイルの読み書き
    #include
    #include
    #include
    
    
    struct Person {
         
    	int height = 666;
    	std::string name = "  ";
    }p;
    
    
    void output_test(std::string);
    void input_test(std::string);
    
    
    int main()
    {
         
    	std::string file_name = "test.txt";
    	output_test(file_name);
    	input_test(file_name);
    }
    
    
    void output_test(std::string file_name) {
         
    	std::ofstream ofs(file_name, std::ios::out | std::ios::binary);
    	ofs.write((const char*)&p, sizeof(p));
    	ofs.close();
    }
    
    void input_test(std::string file_name) {
         
    	std::ifstream ifs(file_name, std::ios::out | std::ios::binary);
    
    	Person p1;
    	if (ifs.is_open())
    	{
         
    		ifs.read((char *)&p1, sizeof(p1));
    	}
    	std::cout << p1.height << p1.name;
    	ifs.close();
    }