C 檔案操作

2021-06-04 17:10:36 字數 1628 閱讀 2808

1、標頭檔案介紹

#include //標準輸入輸出流

#include //派生自iostream,包括ifstream和ofstream

using namespace std;//都在命名空間std中,別忘了加上

2、開啟檔案

const char* filename="1.txt";//要開啟的檔名,可以使路徑名,預設情況下是所建工程下

fstream類派生了兩個類ifstream\ofstream

fstream f(filename,引數二);

引數二有多種形式,這裡只看主要用的幾種:

ios_base::in//開啟檔案用於讀

ios_base::out//開啟檔案用於寫

ios_base::binary//以二進位制方式開啟檔案,預設情況下是文字檔案方式

例:fstream i(filename,ios_base::in|ios_base::out);//開啟檔案用於讀寫(既可讀也可寫)

ifstream in(filename,ios_base::binary|ios_base::in);//以二進位制方式開啟檔案用於讀

3、由於派生自iostream,很多其他的方法和iostream一樣

比如:seekg()\eof()\clear()……

4、一些檔案操作的例子

讀寫二進位制檔案

#include "stdafx.h"

#include #include #include using namespace std;

struct plant

;int _tmain(int argc, _tchar* argv)

return true;}

int _tmain(int argc, _tchar* argv)

while(!f.is_open());

int linecount=1;//記錄當前檔案的總行數

int sumbyte=0;//記錄檔案的總大小

while(!f.eof())

f.clear();

float kb;

kb=(float)sumbyte/1024;

cout<<"當前檔案的位元組數是:"<>str_line;

while(!isdigital(str_line))

line=atoi(str_line.c_str());

cout<<"當前的line值 :"cout<<"你選擇了輸出第"<>c;

}while(c=='y');

// char p;

//cin>>p;

return 0;

}

複製檔案

#include "stdafx.h"

#include #include using namespace std;

const char* file1="1.txt";

const char* file2="2.txt";

//把檔案1的內容寫到檔案2的末尾

int _tmain(int argc, _tchar* argv)

{ ifstream in(file1);//預設方式開啟檔案1進行讀

out<

c++檔案操作就介紹到這裡

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 一般情況下就是指的顯示器...