天天看點

【C++】 fstream 與freopen 小結

轉發自: https://blog.csdn.net/seadplus/article/details/7802346  fstream()解析

https://blog.csdn.net/jacky_chenjp/article/details/70237418  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檔案檢視。