C 從磁碟中讀取檔案

2022-02-15 13:10:31 字數 2367 閱讀 7191

讀取txt檔案

------讀取的資料比較小的時候:

如果你要讀取的檔案內容不是很多,可以使用 file.readalltext(filepath) 或指定編碼方式 file.readalltext(filepath, encoding)的方法。它們都一次性將文字內容全部讀完,並返回乙個包含全部文字內容的字串

用string接收

string str1 = file.readalltext(@"c:\temp\a.txt"); //也可以指定編碼方式

string str2 = file.readalltext(@"c:\temp\a.txt", encoding.ascii);

也可以使用方法file.readalllines,該方法一次性讀取文字內容的所有行,返回乙個字串陣列,陣列元素是每一行的內容

string strs1 = file.readalllines(@"c:\temp\a.txt"); 

// 也可以指定編碼方式

string strs2 = file.readalllines(@"c:\temp\a.txt", encoding.ascii);

-----讀取資料比較大的時候,採用流的方式:

當文字內容比較大時,我們就不要將文字內容一次性讀完,而應該採用流(stream)的方式來讀取內容

。.net為我們封裝了streamreader類,它旨在以一種特定的編碼從位元組流中讀取字元

。streamreader類的方法不是靜態方法,所以要使用該類讀取檔案首先要例項化該類,在例項化時,要提供讀取檔案的路徑。

streamreader sr1 = new streamreader(@"

c:\temp\a.txt

");

// 讀一行

string nextline =sr.readline();

//同樣也可以指定編碼方式

streamreader sr2 = new streamreader(@"

c:\temp\a.txt

", encoding.utf8);

filestream fs = new filestream(@"

c:\temp\a.txt

", filemode.open, fileaccess.read, fileshare.none);

streamreader sr3 = new

streamreader(fs);

streamreader sr4 = new

streamreader(fs, encoding.utf8);

fileinfo myfile = new fileinfo(@"

c:\temp\a.txt");

//opentext 建立乙個utf-8 編碼的streamreader物件

streamreader sr5 =myfile.opentext();

//opentext 建立乙個utf-8 編碼的streamreader物件

streamreader sr6 = file.opentext(@"

c:\temp\a.txt

");

獲取到大的檔案後,都是流的返回形式

可以用流的讀取方法讀出資料,返回型別是string型別

//

讀一行string nextline =sr.readline();

//讀乙個字元

int nextchar =sr.read();

//讀100個字元

int n = 100; char chararray = new

char[n]; int ncharsread = sr.read(chararray, 0

, n);

//全部讀完

string restofstream = sr.readtoend();

使用完streamreader之後,不要忘記關閉它: sr.close();

streamreader sr = file.opentext(@"c:\temp\a.txt"); 

string nextline;

while ((nextline = sr.readline()) != null)

sr.close();

讀取磁碟檔案

例項說明 在程式執行之前,在任意路徑下新建乙個文字文件,文件內容為hello world!程式設計實現從鍵盤中輸入檔案路徑及名稱,在螢幕中顯示出該檔案中的內容。技術要點 用到fopen函式來開啟檔案 file fp fp fopen 檔名,使用檔案的方式 用到fgetc函式 ch fgetc fp ...

文字檔案從磁碟讀取 寫入

using system using system.text using system.io namespace x.common return result 寫入文字檔案,按預設編碼 文字檔案路徑包括檔名 寫入內容 public static void write string filepath,...

WIndows下 C 從檔案中讀取資料

背景 windows下利用c 從檔案中讀寫內容 1 使用fscanf語句 include include std file fp fp fopen filepath.c str r if fp std mapnonamemap fscanf fp,s,s,s a,b,c printf s s s n...