檔案的讀寫

2021-06-05 01:04:37 字數 853 閱讀 1811

為了讀而開啟檔案,要建立乙個ifstream物件,他的用發與cin相同,為了寫而開啟檔案,要建立乙個ofstream物件,用法與cout相同。一旦開啟乙個檔案,就可以像處理其他iostream物件那樣對它進行讀寫。

在iosream庫中,乙個十分有用的函式是getline(),用它可以讀入到string物件中(以換行符結束)。getline()的第乙個引數是ifstream物件,從中讀取內容,第二個引數是stream物件。函式呼叫完成後,string物件就裝載了一行內容。

and firstmain.cpp is the name of sourse file

#include

#include

#include

using namespace std;

int main(int argc, char* argv)

{ifstream in("firstmain.cpp");

ofstream out("firstmain2.cpp");

string s;

while(getline(in,s))

cout<

#include

#include

#include

using namespace std;

int main(int argc, char* argv)

{ifstream in("firstmain.cpp");

ofstream out("firstmain2.cpp");

string s,line;

while(getline(in,line))

s+=line+"\n";

cout《這兩個例子會在控制台輸出源**。

檔案的讀寫

eg 文字中每一行的資料結構,它們是以tab鍵為間隔的 afghanistan baghlan 36.12 68.7 afghanistan balkh 36.758 66.896 include stdafx.h include fstream include using namespace st...

檔案的讀寫

對於檔案的讀寫有各種形式,如位元組流讀寫,字元流讀寫,在字元流之上的緩衝流的讀寫,對於這幾種流的讀寫各有優點,各有不足吧 首先介紹一下位元組輸入輸出流 fileinputstream fiieoutputstream 對檔案的操作 將檔案aa.txt中的內容讀取出來放到bb.txt檔案中。首先以乙個...

檔案的讀寫

getline fin,s 成功讀出一行,把讀出的結果放入s,並返回true,如果到達結束,就返回false getline讀出一行,遇到換行符則終止,將丟棄換行符而不存入s物件 因此,想使得拷貝的檔案和原始檔看上去一樣,必須加上換行符 檔案讀寫示例 include include include ...