fstream文件操作總結
文件的操作一直在用,在此總結一下:fstream的使用
std::fstream從std::ofstream繼承寫入文件的功能,從std::ifstream繼承讀取文件的功能.
包含頭文件
#include <fstream>
- 使用open( )和close( )打開和關閉文件
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream myFile;
//如果不存在即創建新文件
myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::out|ios_base::trunc);
if (myFile.is_open())
cout << "open is ok " << endl;
myFile.close();
system("pause");
}
輸出結果:
open( )函數:第一個參數是要打開的文件的路徑和名稱(或指定當前路徑),第二參數是文件的打開模式。
具體屬性可參考網址
其他文件讀取方式:
//使用構造函數打開
fstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::out | ios_base::trunc);
// 只想打開文件寫入
ofstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::out);
// 只想打開文件讀取
ifstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::in);
2.使用open( )創建及寫入文本,使用運算符<<
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream myFile;
//如果不存在即創建新文件
myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::out|ios_base::trunc);
if (myFile.is_open())
cout << "open is ok " << endl;
// 寫入文本
myFile << "hello fstream" << endl;
cout << "Finished" << endl;
myFile.close();
system("pause");
}
3.使用open( )創建及讀入文本,使用運算符>>
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
fstream myFile;
//如果不存在即創建新文件
myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::in);
if (myFile.is_open())
cout << "open is ok " << endl;
string fileTxt;
while (myFile.good())
{
getline(myFile,fileTxt);
cout << fileTxt << endl;
}
cout << "Finished" << endl;
myFile.close();
system("pause");
}
txt文件內容
輸出