C 檔案操作

2021-07-10 17:34:13 字數 1170 閱讀 3962

1.寫入到文字檔案

必須包含標頭檔案fsream,fstream中定義了乙個用於ofstream類,但要事先宣告自己的ofstream物件,必須指明命名空間std,需要將ofstream物件用open()方法和檔案關聯起來,使用完檔案後用close()方法將其關閉。

程式例項:

#include "stdafx.h"

#include

#include

using namespace std;

int _tmain(int argc, _tchar* argv)

注:若源文字檔案中有其他內容,將清空檔案並寫入。要不清空,以後補充。

2、讀取文字檔案

必須包含標頭檔案fsream,fstream中定義了乙個用於ifstream類,但要事先宣告自己的ifstream物件,必須指明命名空間std,需要將

ifstream物件用open()方法和檔案關聯起來,使用完檔案後用close()方法將其關閉。可以使用ifstream物件和get()方法讀取乙個字元,用getline()方法讀取一行字元。檢查檔案是否成功開啟用is_open()方法。可以用fail()、eof()方法檢查輸入是否成功。

程式例項:

#include "stdafx.h"

#include

#include

#include

using namespace std;

const int size=60;

int _tmain(int argc, _tchar* argv)

double value;

double sum=0.0;

int count=0;

infile>>value;

while(infile.good())

if(infile.eof())

cout<<"end of file"<

else

if(infile.fail())

cout<<"data mismatch"<

else

cout<<"unknown reason"<

if(count==0)

cout<<"no data"<

else

infile.close();

cin.get();

return 0; }

C 檔案操作與C 的檔案操作

c filestream 檔案流 主要用於使用二進位制方式讀寫檔案資料,可讀取任何檔案 建立filestream物件 e 建立filestream物件 filemode 指定系統開啟檔案的方式filestream fileaccess 指定檔案的訪問方式 read唯讀,write只寫,readwri...

C 檔案操作

c 追加檔案 sw.writeline 追逐理想 sw.writeline kzlll sw.writeline net筆記 sw.flush sw.close c 拷貝檔案 string orignfile,newfile file.copy orignfile,newfile,true c 刪除...

C 檔案操作

c 檔案操作 軒軒 發表於 2006 2 18 12 40 16 在c 中,有乙個stream這個類,所有的i o都以這個 流 類為基礎的,包括我們要認識的檔案i o,stream這個類有兩個重要的運算子 1 插入器 向流輸出資料。比如說系統有乙個預設的標準輸出流 cout 一般情況下就是指的顯示器...