日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

C++:文件操作2 文本文件和二进制文件的读写

發布時間:2023/11/27 生活经验 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++:文件操作2 文本文件和二进制文件的读写 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文件讀寫的步驟:

1、包含的頭文件:#include <fstream>//使用文件流進行操作

2、創建流

3、打開文件(文件和流關聯)

4、讀寫 (寫操作:<<,put( ),?write( )?讀操作:?>> , get( ),getline( ), read( ))

5、關閉文件:把緩沖區數據完整地寫入文件, 添加文件結束標志, 切斷流對象和外部文件的連接

---------------------------

文件的讀寫:

1、文本文件的讀寫:

方法:

一次性讀寫若干字符

?????? 1)使用運算符<< 和 >>進行讀寫

?????? 功能:

???????<< 能實現以行為單位寫入文件

?????? >> 不能一行為單位讀入內存,總是以空格、Tab、回車結束,而是以單詞為單位

//函數功能:使用<< ,寫入文件一行字符
#include <fstream>  
#include <iostream>  
using namespace std;
void main()
{ofstream OpenFile("file.txt");//file.txt不需要提前建立存在,執行程序時發現沒有此文件會
//自己創建if (OpenFile.fail()){cout << "打開文件錯誤!" << endl;exit(0);}OpenFile << "abc def ghi";OpenFile.close();system("pause");
}

程序執行結果:文件中寫入內容:abc def ghi

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

//函數功能:使用>>,從文件讀入一個單詞
#include <fstream>  
#include <iostream>  
using namespace std;
void main()
{const int len = 20;char str[len];ifstream OpenFile("file.txt");//必須是實現建立好已經存在的文件,否則打開文件錯誤if (OpenFile.fail()){cout << "打開文件錯誤!" << endl;exit(0);}OpenFile >> str;  //此處并不是讓你輸入,而是從文件中讀取cout << str << endl;OpenFile.close();system("pause");
}

運行結果:str的內容為abc,而不是abc def ghi(見空格停止)

如果file.txt該文本中為空,則執行程序的結果為左圖(表明文中第15行并不是類似于cin的從鍵盤輸入操作,而此處是從文件中讀取)。 ?? 如果file.txt該文本中是第一個程序執行后的結果,該程序執行結果如右圖。

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

2)使用運算符<<(寫)和getline()進行讀寫

???????功能:

???????<<:以行為單位輸入文件

?????? getline():以行為單位?讀入內存,能一次讀入一行

???????函數原型:istream &getline( char *buffer, streamsize num );

?????? 功能:getline( )函數用于從文件讀取num-1個字符到buffer(內存)中,直到下列情況發生時,讀取結束:

?????? 1):num - 1個字符已經讀入

???????2):碰到一個換行標志

?????? 3):碰到一個EOF

/*getline()的原型是istream& getline ( istream &is , string &str , char delim );會生成一個包含一串從輸入流讀入的字符的字符串,
?直到以下情況發生會導致生成的此字符串結束:1)到文件結束,2)遇到函數的定界符,3)輸入達到最大限度。
getline(<字符數組chs>,<讀取字符的個數n>,<終止符>)*/

//使用運算符<<(寫)和getline()進行讀寫
#include <fstream>  
#include <iostream>  
using namespace std;  
void main()  
{  const int len=20;  char str[len];  ifstream OpenFile("file.txt");  if (OpenFile.fail())  {  cout<<"打開文件錯誤!"<<endl;  exit(0);  }  OpenFile.getline(str,20);  cout<<str<<endl;  OpenFile.close();  system("pause");  
} 

運行結果:str的內容為abc def ghi (一直把一行讀完)

------使用讀取整行文本的函數。全局函數 getline() 可以用于此目的,它也是字符串庫的一部分。其用法如下。

istream& getline (istream& is, string& str, char delim = '\n');

該函數從流 is 中讀取一行文本,并將其存儲到字符串變量 str 中。該函數具有一個可選的形參 delim,用于標記要讀取的行的結尾。分隔字符被從流中移除并丟棄。如果在沒有第 3 個形參的情況下調用 getline,則分隔符被認為是行尾字符 '\n'。

第一個參數 is,必須是 istream 類的一個對象。它也可以是 istringstream、ifstream 或 fstream 類中的任何對象(如果傳遞了 fstream 對象,則必須打開它才能輸入)。返回的值是對剛剛讀取的輸入流的引用。這允許測試返回值以確定調用的成功或失敗,如下面的代碼段所示:

string str;
if (getline(inputstream, str))
{//讀取一行并存儲到str中cout << str << endl;
}
else
{//出現錯誤或到達文件末尾
}

或者,也可以忽略返回值并在調用后的語句中測試流:

string str;
getline(inputstream, str);
if (inputstream)
{//讀取一行并存儲到str中cout << str << endl;
}
else
{//出現錯誤或到達文件末尾
}

使用 getline 函數逐行讀取文件,從而保留了單詞之間的白色空格:

// This program uses the getline function to read a line of information from the file.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{// Variables needed for file inputfstream nameFile;string input;// Open the filenameFile. open ("murphy.txt" , ios::in);if (!nameFile){cout << "File open error!" << endl;return 0;}// Read first line of the filegetline(nameFile, input);//該函數從流 nameFile 中讀取一行文本,并將其存儲到字符串變量 input 中while (nameFile){//If successful, print line and read another linecout << input << endl;getline(nameFile, input);}// Close the filenameFile.close();return 0;
}

提前建立的murphy.txt文檔內容如左邊; ? 程序執行結果如右邊。

? ? ? ? ? ? ? ? ??

由于 getline 函數的第 3 個參數在此程序中被省略了,所以它的默認值是 \n。有時可能想要指定另一個分隔符。例如,來看一個包含多個名稱和地址的文件,比如存在一個addresses.txt,其內部格式如下:

可以將該文件看成是由 3 個記錄組成的。記錄是關于單個項目的完整信息集。另外,文件中的記錄由 3 個字段組成:

  • 第一個字段就是某人的名字;
  • 第二個字段是某人的街道地址或郵政信箱號碼;
  • 第三個字段包含某人的城市、州和郵政編碼。

PS:請注意,每個字段以 $ 字符結尾,每個記錄以 \n 字符結尾。下面的程序演示了如何使用 getline 函數來檢測 $ 字符:

// This file demonstrates the getline function with a user-specified delimiter.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;int main()
{// Variable needed to read filestring input;// Open the file.fstream dataFile ("addresses.txt", ios::in);if (!dataFile){cout << "Error opening file.";return 0;}// Read lines terminated by '$'' sign and outputgetline(dataFile, input, '$');//$用于標記要讀取的行的結尾while (!dataFile.fail()) //判斷是否存在有效的輸入流{cout << input << endl;  //輸出檢測到的第一個$之前的內容  并進行換行getline(dataFile, input, '$');//再次調用getline函數}// Close the filedataFile.close ();return 0;
}

此程序輸出結果為:

請注意,標記每個記錄結尾的 \n 字符也是輸出的一部分。它們會在屏幕上打印出額外的空白行,將記錄分開。

另外,使用 $ 之類的可打印字符分隔文件中的信息時,請務必選擇一個實際上不會出現在信息本身中的字符。由于任何人的姓名或地址含有 $ 字符都是值得懷疑的,所以在這里它是一個可接受的分隔符。但如果文件中包含美元金額,則應該選擇另一個分隔符。

while(getline())見鏈接:

https://mp.csdn.net/console/editor/html/104759846

?

?

?

?

?

?

?

一次讀寫一個字符:

使用get( )和put( )函數

函數聲明:istream& get(char &c);

//使用 get( )函數 把字符1輸入到文件
#include <fstream>  
#include <iostream>  
using namespace std;  
void main()  
{  char ch='1';  ofstream OpenFile("file.txt");  //該file.txt文檔不需要提前建立,檢測到沒有此文件會自動創建if (OpenFile.fail())  {  cout<<"打開文件錯誤!"<<endl;  exit(0);  }  OpenFile.put(ch);  OpenFile.close();  system("pause");  
}  

運行結果:把字符1寫入文件

//函數功能:使用 put( )函數 把文件中第一個字符輸入內存
#include <fstream>  
#include <iostream>  
using namespace std;  
void main()  
{  char ch;  ifstream OpenFile("file.txt");  //需要提前存在file.txtif (OpenFile.fail())  {  cout<<"打開文件錯誤!"<<endl;  exit(0);  }  OpenFile.get(ch);  cout<<ch;  OpenFile.close();  system("pause");  
}  

運行結果:把字符1從文件中讀到ch(內存)中

第15行不加<<endl輸出結果為左圖。 ? 加入輸出結果如右圖。? PS:就是一個換行的功能

? ? ? ? ? ? ? ? ? ? ? ??

2、二進制文件的讀寫:

? 1)使用運算符get( )?和 put( )讀寫一個字節

功能:

?????? get( )?:在文件中讀取一個字節到內存

函數原型:ifstream &get(char ch)

?????? put( ) :在內存中寫入一個字節到文件

函數原型:ofstream &put(char ch)

//功能:把26個字符寫入文件中
#include <fstream>  
#include <iostream>  
using namespace std;  
void main()  
{  char ch='a';  ofstream OpenFile("file.txt",ios::binary);  //file.txt此文檔無需提前建立好,檢測到不存在會自動進行創建if (OpenFile.fail())  {  cout<<"打開文件錯誤!"<<endl;  exit(0);  }  for (int i=0;i<26;i++)  {  OpenFile.put(ch);  ch++;  }  OpenFile.close();  system("pause");  
}  

運行結果:文件內容為abcdefghijklmnopqlst...z

? ? ? ? ? ? ? ? ? ? ? ?

//功能:把文件中的26個字母讀入內存
#include <fstream>  
#include <iostream>  
using namespace std;  
void main()  
{  char ch;  ifstream OpenFile("file.txt",ios::binary); //file.txt需要提前建立存在 ,否則打開文件錯誤if (OpenFile.fail())  {  cout<<"打開文件錯誤!"<<endl;  exit(0);  }  while (OpenFile.get(ch))  cout<<ch;  OpenFile.close();  system("pause");  
}  

運行結果:ch依次為abc...z ? ? ? ? PS:加入換行符<<endl的不同輸出結果。

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

2)使用read()和write()進行讀寫

  read( ):

?????? 功能:從文件中提取 n 個字節數據,寫入buf指向的地方中

?????? 函數聲明:istream &? read ( char * buf ,? int? n ) ;

? ? ? write( ):

????? 功能:把buf指向的內容取n個字節寫入文件

??????函數聲明:ostream & ostream :: write ( char * buf ,? int? n ) ;

????? 參數說明:buf表示要寫入內存的地址,傳參時要取地址。n表示要讀入字節的長度

????? 注意:1):該函數遇到空字符時并不停止,因而能夠寫入完整的類結構

????????????????? 2):第一個參數一個char型指針(指向內存數據的起始地址),與對象結合使用的時候,要在對象地址之前要char做強制類型轉換。?

//函數功能:使用write( )函數,一次從內存向文件寫入一行數據
#include <fstream>  
#include <iostream>  
using namespace std;  
void main()  
{  char ch[12]="12 3 456 78";  ofstream OpenFile("file.txt");  //不需要提前建立file.txt文件,檢測到不存在會自動建立,如果提前存在,會覆蓋掉原來的file.txt重新建立一個。if (OpenFile.fail())  {  cout<<"打開文件錯誤!"<<endl;  exit(0);  }  OpenFile.write(ch,12);  OpenFile.close();  system("pause");  
}  

運行結果:文件內容12 3 456 78

將OpenFile.write(ch,12)改變參數為OpenFile.write(ch,8),程序執行結果如右圖只讀取8個字節長度。

? ? ? ? ? ? ? ?

//函數功能:使用read()函數從文件中提取 n 個字節數據,寫入buf指向的地方中
#include <fstream>  
#include <iostream>  
using namespace std;  
void main()  
{  char ch[12];  ifstream OpenFile("file.txt");  //需要提前存放好數據文檔if (OpenFile.fail())  {  cout<<"打開文件錯誤!"<<endl;  exit(0);  }  OpenFile.read(ch,12);  cout<<ch;  OpenFile.close();  system("pause");  
}  

原始建立的文件為:

此種情況原始文件本來就存在一行:

OpenFile.read(ch,12);此中條件下的兩種結果:(因為是按照字節讀取,整行讀取,所以整行數據并未拆分)

? ? ??

? ? ? ? ??

將原始文件增加為兩行:

OpenFile.read(ch,12);此中條件下的兩種結果:

? ?? ? ? ? ? ? ? ? ? ? ? ? ?

? ? ? ? ? ? ? ? ? ? ?

沒有讀取第二行文本,因為字節數12跟8在限制。

? ? ? ? ? ? ? ? ?

------PS:

1、程序不再使用文件時,為什么要關閉文件?

因為:1)文件緩沖區是一塊小的內存空間.

????????????2)操作系統限制同時打開的文件數量?

注意:close ( ) 函數關閉文件,但流對象仍然存在。

2、文件的默認打開方式為文本文件,要是想以二進制的方式處理,在打開時要用 ios::binary 顯式聲明。

3、針對文本文件操作時,get函數和>>的區別:

區別:在讀取數據時,get函數包括空白字符(遇空白字符不停止讀取)

??????????? >>在默認情況下拒絕接受空白字符(遇到空白符停止讀取)

4、判斷文件是否打開的方法:

//判斷文件是否打開的方法:
if (OpenFile)  
{  cout<<"打開文件失敗!";  exit(0);  
}  
if (OpenFile.fail())  
{  cout<<"打開文件錯誤!"<<endl;  exit(0);  
}  

5、判斷文件是否結束的方法:

//方法1)使用成員函數eof()可以檢測到這個結束符,如果非0表示文件結束。while (!OpenFile.eof())  {  //文件結束時的代碼  }  
//2)使用流直接檢測,如果為0表示文件結束
while (!OpenFile)  {  //文件結束時的代碼  }  
//3)使用get函數,讀取最后一個結束符時,返回0.讀取正常情況下,返回1,并把讀取的字符放到ch中
while ( (OpenFile.get(ch) )!=EOF)  {  //成功時候的代碼  }  

文本文件的讀寫常使用的方法:使用<<寫入文件,使用getline 和 >> 讀到內存

二進制文件的讀寫常使用的方法:使用istream 類的成員函數read 和write 來實現,

這兩個成員函數的原型為:

istream& read(char *buffer,int len);  
ostream& write(const char * buffer,int len);   

上述參數說明:字符指針 buffer 指向內存中一段存儲空間。len 是讀/寫的字節數。

與對象結合寫入二進制文件時:

//write函數調用語句:
輸出文件流對象名.write((char*)& 對象名,sizeof(<對象所屬類名>));  
輸出文件流對象名.write((char*)& 對象數組名[下標],sizeof(<對象所屬類名>));  
//read函數調用語句:
輸入文件流對象名.read((char*)& 對象名,sizeof(<對象所屬類名>));          
輸入文件流對象名.read((char*)& 對象數組名[下標],sizeof(<對象所屬類名>));  

PS:gcount()函數經常和read函數配合使用,用來獲得實際讀取的字節數。? ? ?

//二進制文件的隨機讀寫
#include <iostream>  
#include <fstream>  
using namespace std;  
int main(void)  
{  //寫文件:二進制存儲1234  int writeNum1 = 1;  int writeNum2 = 2;  int writeNum3 = 3;  int writeNum4 = 4;  ofstream fout("test.txt", ios::out | ios::binary);  fout.write(reinterpret_cast<char *>(&writeNum1), sizeof(int));  fout.write(reinterpret_cast<char *>(&writeNum2), sizeof(int));  fout.write(reinterpret_cast<char *>(&writeNum3), sizeof(int));  fout.write(reinterpret_cast<char *>(&writeNum4), sizeof(int));  fout.close();  //讀文件  ifstream fin("test.txt",ios::in | ios::binary);  if (!fin.good())  {  cout<<"文件打開錯誤"<<endl;    exit(0);  }  int readNum = 0;  //第一次輸出:從第一個數字輸出,結果是1 2 3 4  fin.seekg(0,ios::beg);  while (fin.peek() != EOF)  {  fin.read(reinterpret_cast<char*>(&readNum), sizeof(int));  cout<<readNum<<" ";  }  cout<<endl;  //第二次輸出:從第三個數字輸出,結果是3 4 fin.seekg(2 * sizeof(int),ios::beg);//游標移動的次數 = 需要處理數的個數 × int占的字節數  while (fin.peek() != EOF)  {  fin.read(reinterpret_cast<char*>(&readNum), sizeof(int));  cout<<readNum<<" ";  }  cout<<endl;  fin.close();  system("pause");  return 0;  
}  

? ? ? ? ? ? ? ? ? ? ? ? ?

?

?

總結

以上是生活随笔為你收集整理的C++:文件操作2 文本文件和二进制文件的读写的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。