1. 程式人生 > >c++讀寫txt與dat檔案

c++讀寫txt與dat檔案

1、建立dat/txt檔案(若dat檔案不存在時)並向其中寫入資料

#include <string>
#include <iostream>  
#include <fstream>  
using namespace std;

int main()  
{
    ofstream outfile("E:\\myfile.dat", ofstream::app); 
    //ofstream outfile("E:\\myfile.txt", ofstream::app);  

    string temp = "O \nM \nG \n!";  //寫入內容
if(outfile.is_open()) { outfile<<temp<<"\n"; outfile.close(); } else { cout<<"can not open the file \n"<<endl; return -1; } return 0; }

2、讀取dat/txt檔案中的資料

#include <string>
#include <iostream>  
#include <fstream> using namespace std; int main() { ifstream infile("E:\\myfile.dat"); //ifstream infile("E:\\myfile.txt"); string temp; if (!infile.is_open()) { cout<<"can not open the file \n"<<endl; return -1; } while(getline(infile,temp)) { cout
<<temp<<"\n"; } infile.close(); return 0; }