C++ 標准文件的寫入讀出(ifstream,ofstream)


 

 

 
注: "<<", 插入器,向流輸入數據
      ">>", 析取器,從流輸出數據,
 
ifstream和ofstream主要包含在頭文件<fstream>中. fstream可對打開的文件進行讀寫操作
ifstream <===> 硬盤向內存寫入文件
ofstream <===> 內存向硬盤寫入文件
ofstream out("out.txt");

if(out.is_open())    //is_open()返回真(1),代表打開成功

{

    out<<"HELLO WORLD!"<<endl;

    out.close();

}

在文件out.txt中寫入了HELLO WORLD!

 

ifstream in("out.txt");

cha buffer[200];

if(in.is_open())

{

    while(!in.eof())

    {

        in.getline(buffer,100)

        cout<<buffer<<endl;

        out.close();

    }

}

 

打開文件:
 
 
ofstream out("/root/1.txt"); 
或者 
ofstream out;
out.open("/root/1.txt");
 
寫入:
out << "hello, world!!!" << endl;
 
 
關閉文件:
 
 
out.clear(); //為了代碼具有移植性和復用性, 這句最好帶上,清除標志位.有些系統若不清理可能會出現問題.
out.close();
 
//對於上面兩語句的先后問題.取決於文件打開是否成功,若文件打開失敗.先clear后再直接close的話狀態位還是會出現問題.. 一般邏輯是先close,不管close成功與否,然后clear清楚標志位
 
文件打開狀態的判斷(狀態標識符的驗證):
.bad() <===> 讀寫文件出錯, 比如以r打開寫入,或者磁盤空間不足, 返回true
.fail() <===> 同上, 且數據格式讀取錯誤也返回true
.eof() <===> 讀文件到文件結尾,返回true
.good() <===> 最通用,如果上面任何一個返回true,則返回false.
如果清除上面標志位,則調用.clear()函數
 
實例完整代碼:
 
 
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>

using namespace std;
#define TO_NUMBER(s, n) (istringstream(s) >> n)    //字符串轉換為數值
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())    //數值轉換為字符串

int main(int argc, char **argv)
{
	string lines;
    ifstream infile(argv[1]);
	ofstream outfile(argv[2]);
	
	if(!infile.is_open())
	{
		cout<<argv[1]<<"文件打開失敗"<<endl;
		return 0;
	}
	
	if(!outfile.is_open())
	{
		cout<<argv[2]<<"文件打開失敗"<<endl;
		return 0;
	}
	
	while(getline(infile,lines))
	{
		if(infile.eof())
		{
			cout<<"文件讀取失敗"<<endl;
			break;
		}
		
		istringstream strline(lines);
		string tmp_string;
		int i = 1;
		
		strline>>tmp_string;
		string linename = tmp_string;
		while(strline>>tmp_string)
		{
			outfile<<"#	"<<i<<"	"<<linename<<"	"<<i<<"	"<<tmp_string<<endl;;
			i++;
		}
		cout<<"total column is: "<<i<<endl;
	}

    
	infile.clear(); //為了代碼具有移植性和復用性, 這句最好帶上,清除標志位.有些系統若不清理可能會出現問題.
	infile.close();
	outfile.clear(); //為了代碼具有移植性和復用性, 這句最好帶上,清除標志位.有些系統若不清理可能會出現問題.
	outfile.close();
	
    return 0;
}

 

 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM