1. 程式人生 > >【C++】 fstream 與freopen 小結

【C++】 fstream 與freopen 小結

  1. C++檔案流:
fstream  // 檔案流
ifstream  // 輸入檔案流
ofstream  // 輸出檔案流

#include <fstream>
 
//建立一個文字檔案並寫入資訊
//同向螢幕上輸出資訊一樣將資訊輸出至檔案
#include<iomanip.h>
#include<fstream>
 
void main()
{
ofstream ofs("C:\\example.txt");           //開啟檔案用於寫,若檔案不存在就建立它
if (!ofs) return;                  //開啟檔案失敗則結束執行
 
f1 << setw(20) << "Name: " << "Beethoven" << endl;     //使用插入運算子寫檔案內容
f1 << setw(20) << "song: " << "Moonlight Sonata" << endl;
f1.close();                   //關閉檔案
}

檔案操作:【檔案開啟選項】

ios::in    = 0x01, //供讀,檔案不存在則建立(ifstream預設的開啟方 式)
ios::out    = 0x02, //供寫,檔案不存在則創 建,若檔案已存在則清空原內容(ofstream預設的開啟方式)
ios::ate    = 0x04, //檔案開啟時,指標在檔案最後。可改變指標的位置,常和in、out聯合使用
ios::app    = 0x08, //供寫,檔案不存在則建立,若檔案已存在則在原檔案內容後寫入 新的內容,指標位置總在最後
ios::trunc   = 0x10, // 在讀寫前先將檔案長度截斷為0(預設)
ios::nocreate = 0x20, //檔案不存在時產生錯誤,常和in或app聯合使用
ios::noreplace = 0x40, //檔案存在時產生錯誤,常和out聯合使用
ios::binary  = 0x80  //二進位制格式檔案

檔案保護方式選擇項:


filebuf::openprot;   //預設的相容共享方式
filebuf::sh_none;    //獨佔,不共享
filebuf::sh_read;    //讀共享
filebuf::sh_write;   //寫共享

開啟檔案的方法
呼叫建構函式時指定檔名和開啟模式

ifstream f("d:\\12.txt", ios::nocreate);   //預設以 ios::in 的方式開啟檔案,檔案不存在時操作失敗
ofstream f("d:\\12.txt");           //預設以 ios::out的方式開啟檔案
fstream  f("d:\\12.dat", ios::in|ios::out|ios::binary); //以讀 寫方式開啟二進位制檔案

使用Open成員函式

fstream f;
f.open("d:\\12.txt",ios::out);  //利用同一物件對多個檔案進行操作時要用到open函式

檢查是否成功開啟
成功:

if (f) {...}  //對ifstream、ofstream物件可 用,fstream物件不可用。 mysql
if (f.good()) {...}

失敗:

if (!f) {...}       //!運算子過載
if (f.fail()) {...}

讀寫操作
使 用<<,>>運算子
只能進行文字檔案的讀寫操作,用於二進位制檔案可能會產生錯誤。
使用函式成員 get、put、read、write等
經常和read配合使用的函式是 gcount(),用來獲得實際讀取的位元組數。

讀寫二進位制檔案注意事項
開啟方式中必須指定ios::binary,否則讀寫會出錯
用read\write進行讀寫操作,而不能使用插入、提取運算子進行操作,否則 會出錯。
使用eof()函式檢測檔案是否讀結束,使用gcount()獲得實際讀取的位元組數

關閉檔案
使用成員函式close, 如: oracle
f.close(); 
利用解構函式
物件生命期結 束時會檢查檔案是否關閉,對沒有關閉的檔案進行關閉操作。

隨機讀寫檔案
通過移動檔案讀寫指標,可在檔案指定位置進行讀寫。

seekg(絕對位置);      //絕對移動,    //輸入流操作
seekg(相對位置,參照位置);  //相對操作
tellg();          //返回當前指標位置
seekp(絕對位置);      //絕對移動,    //輸出流操作
seekp(相對位置,參照位置);  //相對操作   
tellp();          //返回當前指標位置                                

參照位置: mysql

ios::beg  = 0       //相對於檔案頭
ios::cur   = 1       //相對於當前位置
ios::end  = 2       //相對於檔案尾                         

 寫文字檔案的示例
//為能夠正確讀出寫入檔案的各資料,各資料間最好要有分隔

#include<fstream>
 
void main()
{
fstream f("d:\\try.txt", ios::out);
f << 1234 << ' ' << 3.14 << 'A' << "How are you"; //寫入資料
f.close();
f.open("d:\\try.txt", ios::in);
int i;
double d;
char c;
char s[20];
f >> i >> d >> c;               //讀取資料
f.getline(s,20);
cout << i << endl;             //顯示各資料
cout <<d << endl;
cout << c << endl;
cout << s << endl;
f.close();
}
                        


運 行結果:
1234
3.14
A
How are you
Press any key to continue

顯示文字檔案的內容

//使用get()一次讀一個字元--------------------------------方案一
#include<fstream>
 
 
void main()
{
ifstream fin("d:\\簡介.txt", ios::nocreate);
if (!fin) {
cout << "File open error!\n";
return;
}
char c;
while ((c=fin.get()) != EOF) cout << c;    //注意結束條件的判斷
fin.close();
}
            

//使用get(char *,int n,char delim='\n')一次讀多個字元----方案二
//巧妙利用文字檔案中不會有字元'\0'的特點進行讀取

#include<fstream>
void main()
{
ifstream fin("d:\\簡介.txt",ios::nocreate);
if(!fin){
cout<<"File open error!\n";
return;
}
char c[80];
while(fin.get(c,80,'\0')!=NULL)cout<<c; //注意結束條件的判斷
fin.close();
}
//使用read(char *,int n)讀檔案---------------------------方案三
#include<fstream.h>
void main()
{
ifstream fin("d:\\簡介.txt",ios::nocreate);
if(!fin){
cout<<"File open error!\n";
return;
}
char c[80];
while(!fin.eof())            //判 斷檔案是否讀結束
{
fin.read(c,80);
cout.write(c,fin.gcount());
}
fin.close();
}       

拷貝檔案
//二進位制檔案操作示例 ssh

#include<fstream>
 
void main()
{
ifstream fin("C:\\1.exe", ios::nocreate|ios::binary);
if (!fin) {
cout << "File open error!\n";
return;
}
ofstream fout("C:\\2.exe", ios::binary);
char c[1024];
while (!fin.eof())
{
fin.read(c, 1024);
fout.write(c, fin.gcount());
}
fin.close();
fout.close();
cout << "Copy over!\n";
}

 一個開啟並檢查輸入檔案的程式:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
ifstream& open_file(ifstream &in,const string &file)
{
	in.close();
	in.clear();
	in.open(file.c_str());
	return in;
}
int main()
{
	ifstream file;
	open_file(file,"1.txt");
	string s;
	while(getline(file,s))
	{
		cout<<s<<endl;
	}
	file.close();
	return 0;
}
  1. freopen

函式名:freopen

標準宣告:FILE *freopen( const char *path, const char *mode, FILE *stream );

所在檔案:<stdio.h>

引數說明:

        path:檔名,用於儲存輸入輸出的自定義檔名。

        mode:檔案開啟的模式。和fopen中的模式(如 r-只讀, w-只寫)相同。

        stream:一個檔案,通常使用標準流檔案。

        返回值:成功,返回指向檔案的指標;失敗,返回NULL

        功能:實現重定向,把預定義的標準流檔案定向到由path指定的檔案中。

                   標準流檔案具體是指stdin、stdout和stderr。

                   其中stdin是標準輸入流,預設為鍵盤;

                   stdout是標準輸出流,預設為螢幕;

                   stderr是標準錯誤流,預設為螢幕;

下面以在VC下除錯“計算a+b”的程式舉例。 

C語法:

#include <stdio.h>
int main() 
{ 
	int a,b; 
	freopen("D:\\in.txt","r",stdin); //輸入重定向,輸入資料將從D盤根目錄下的in.txt檔案中讀取 
	freopen("D:\\out.txt","w",stdout); //輸出重定向,輸出資料將儲存在D盤根目錄下的out.txt檔案中 
	while(scanf("%d %d",&a,&b)!=EOF) 
	printf("%d\n",a+b); 
	fclose(stdin);//關閉重定向輸入 
	fclose(stdout);//關閉重定向輸出 
	return 0; 
} 

C++語法:

#include <stdio.h>
#include <iostream>
int main()
{ 
	int a,b; 
	freopen("D:\\in.txt","r",stdin); //輸入重定向,輸入資料將從D盤根目錄下的in.txt檔案中讀取 
	freopen("D:\\out.txt","w",stdout); //輸出重定向,輸出資料將儲存在D盤根目錄下的out.txt檔案中 
	while(cin>>a>>b) 
	cout<<a+b<<endl; // 注意使用endl 
	fclose(stdin);//關閉重定向輸入
	fclose(stdout);//關閉重定向輸出 
	return 0; 
}

  freopen("D:\\out.txt","w",stdout)的作用就是把stdout重定向到D:\\out.txt檔案中,這樣輸出結果就可以通過開啟out.txt檔案檢視。