c++中的文件读写的操作
生活随笔
收集整理的這篇文章主要介紹了
c++中的文件读写的操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫文件
讀文件
ifstream ifs
指定打開方式ios::in
isopen判斷是否打開成功
讀取有三種方式
#include<iostream>using namespace std;//文件讀寫頭文件#include<fstream>//寫文件void test01(){//以輸出的方式打開文件//ofstream ofs("./test.txt", ios::out |ios::trunc);//后期指定打開方式ofstream ofs;ofs.open("./test.txt", ios::out | ios::trunc);//判斷是否打開成功if (ofs.is_open()){cout << "打開失敗" << endl;}ofs << "姓名:abc" << endl;ofs << "年齡:100" << endl;ofs << "性別:男" << endl;ofs.close();}//讀文件void test02(){ifstream ifs;ifs.open("./test.txt", ios::in);//是否打開成功if (!ifs.is_open()){cout << "打開失敗" << endl;}//第一種方式//char buf[1024];//while (ifs>>buf)//按行讀//{// cout << buf << endl;//}//第二種方式//char buf2[1024];//while (!ifs.eof())//eof讀到文件尾//{// ifs.getline(buf2, sizeof(buf2));// cout << buf2 << endl;//}//第三種 不推薦 按單個字符讀取char c;while ((c=ifs.get())!=EOF)//EOF文件尾{cout << c;}ifs.close();}int main(){//test01();test02();system("pause");return 0;}總結
以上是生活随笔為你收集整理的c++中的文件读写的操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 地下城从八十升到八十五要多少时间
- 下一篇: c++的STL--1概念通述