C (七)基礎篇 基本I O操作

2022-07-11 04:30:14 字數 1840 閱讀 7420

c#

本隨筆為個人複習鞏固知識用,多從書上總結與理解歸納得來,如有錯誤麻煩指正

i/o操作主要針對計算機檔案的建立和修改,基本包括建立檔案、讀寫檔案和刪除檔案。

1.寫檔案

寫檔案即是將資料存入到乙個檔案的過程。

static

void main(string

args)

2.讀檔案讀取檔案時需要參考寫檔案的過程,按照寫檔案時候的文字格式將資料讀出來。要注意的是先用exists判斷是否存在對應檔案,然後將資料讀入到string陣列中,最後在控制台上顯示。

//

儲存檔案的路徑和檔名

string file = "

d:";

if(system.io.file.exists(file))

console.readkey();

//按任意鍵退出

3.刪除檔案

//

儲存檔案的路徑和檔名

string file = "

d:";

if(system.io.file.exists(file))

4.二進位制讀寫任何資料型別都可以將其轉換為byte存入到陣列中,然後寫入到檔案中,讀取回來時再轉為正確的資料型別來使用。

string file = "

d:\\test.dat

";//

儲存檔案的路徑和檔名

//需要儲存的資料

int data1 = 100

;

float data2 = 0.1f

; filestream fs = new filestream(file, filemode.create); //

建立新檔案

binarywriter bw = new binarywriter(fs); //

二進位制寫入器

bw.write(data1);

bw.write(data2);

//將資料寫入檔案中

bw.close();

fs.close();

//注意關閉檔案

fs = new filestream(file, filemode.open);//

讀取檔案

binaryreader br = new binaryreader(fs);//

二進位制讀取器

int readint = br.readint32();//

注意讀的順序要和寫的一致

float readfloat =br.readsingle();

br.close();

fs.close();

console.writeline(",

", readint, readfloat);//

列印資料

console.readkey();

//按任意鍵退出

書中重點強調了io操作在程式開發中的重點地位,列出了最常用的幾個類。分別是filesteam(檔案流)、fileinfo、file(功能近似fileinfo,但全部靜態實現)、directoryinfo,directory(功能和directory類似,但全部靜態實現)、path(處理路徑名稱)等。

之後會另開篇章講述。

io 基本操作

1 io 可以分為 位元組流 字元流 例子 位元組流 讀乙個寫乙個 得到檔案 file file new file d test.txt try out.flush in.close out.close catch filenotfoundexception e catch ioexception ...

C語言之基本IO操作

include include 讀取文字檔案 int main char path users shaoshuaima workspace xcode c 01 c 01 files friends.txt file fp fopen path,r if fp null printf 檔案開啟失敗....

標準IO操作基礎函式基本使用

說明 fopen,fdopen,freopen stream open functions include file fopen const char pathname,const char mode 例子1 include include include include intmain puts ...