此文是fishc大佬第四堂課的內容小結,學到了很多,來總結一下。
利用c語言編寫乙個檔案複製的程式,如下所示。
#include #include int main( int argc, char* argv )
/*argc和argv
在程式中,main函式有兩個引數,整型變數argc和字元指標陣列argv。
argc的含義是程式的引數數量,包含本身。
argv的每個指標只想命令列的乙個字串,所以argv指向字串「copyfile.exe」
argv[1]指向字串sourcefile,argv[2]只想字串destfile。
*/ if( ( in = fopen( argv[1], "rb") ) == null )
/*通過fopen()函式我們以二進位制的形式按照可讀/可寫方式開啟兩個檔案
並返回兩個檔案指標給in和out
*/if( ( out = fopen( argv[2], "wb") ) == null )
while( (ch = getc(in)) != eof ) // eof == end of file
/*getc()函式一次從輸入流(stdin)讀取乙個字元
putc()函式把這個字元寫到輸出流(stdout)*/}
if( ferror( in ) )
if( ferror( out ))
printf("成功複製1個檔案!\n");
fclose( in );
fclose( out );
return 0;
}
沒什麼好特別說明的,注釋已經寫到了程式當中。
基本的檔案讀寫操作:
ifstream in;以及in.open("test.txt")
ofstream out;以上**在建立乙個ifstream和ofstream類的物件時,將檔案的名字傳遞給它們的建構函式。out.open("test.txt")
下面給出乙個接收兩個引數的例項:
ifstream in(char* filename,int open_mode)其中:filename表示檔案的名稱,它是乙個字串;open_mode表示開啟模式,其值用來定義以怎麼樣的方式開啟檔案(跟open的引數一樣)
下面給出幾種常見的開啟模式:
ios::in -- 開啟乙個可讀取檔案如果需要不只是一種開啟方式,而是需要多種開啟模式的話,可以用 or操作符: |ios::out -- 開啟乙個可寫入檔案
ios::binary -- 以二進位制的形式開啟乙個檔案。
ios::trunc -- 刪除檔案原來已經存在的內容
ios::nocreate -- 如果要開啟的檔案並不存在,那麼以此引數呼叫open函式將無法進行。
ios::noreplace -- 如果要開啟的檔案已經存在,那麼試圖以此引數呼叫open函式將返回乙個錯誤。
而為什麼可以使用or操作符來選擇多種開啟模式呢,來看一段栗子:
#include #include using namespace std;
int main()
fp << "ilovefishc.com!";
static char str[100];
fp.seekg(ios::beg); // 使得檔案指標指向檔案頭 如果ios::end 則是檔案尾。
fp >> str;
cout << str << endl;
fp.close();
return 0;
}
其中利用 | 選擇了ios::in 和ios::out 兩種開啟模式,我們首先編譯這段程式,然後右鍵ios::in 選擇轉到定義,可以看到ios_base.h檔案,其中可以看到如下定義:
typedef _ios_openmode openmode;
/// seek to end before each write.
/// open and seek to end immediately after opening.
static const openmode ate = _s_ate;
/// perform input and output in binary mode (as opposed to text mode).
/// this is probably not what you think it is; see
///
static const openmode binary = _s_bin;
/// open for input. default for @c ifstream and fstream.
static const openmode in = _s_in;
/// open for output. default for @c ofstream and fstream.
static const openmode out = _s_out;
/// open for input. default for @c ofstream.
static const openmode trunc = _s_trunc;
以及:
enum _ios_openmode
;
可以發現定義成了乙個列舉型別,其中1作為long int處理,佔4byte,在此基礎上,將1二進位制左移不同的位數,在使用時進行or操作的話具有唯一性。
cin物件有幾個專門用來報告其工作情況的成員函式,它們將返回乙個真/假值來表明cin的狀態。
-eof() : 如果到達檔案(或輸入)末尾,那麼返回true;-fail() : 如果cin無法工作,返回true;
-bad() : 如果cin因為比較嚴重的原因(例如記憶體不足)而無法工作,返回true;
-good() : 如果上述情況均未發生,返回true。
C入門向 檔案操作
將ascii碼表輸入到文字檔案中 1 127 將a文字檔案的內容輸入到b文字檔案中 將文字檔案的內容輸出到螢幕上 對檔案進行簡易加密 輸出ascii碼對照表 include include int main void fclose f1 return 0 include include int ma...
c語言入門 《檔案操作》
3 關閉檔案 總結開啟檔案函式 fopen const char const char 第乙個引數 檔案路徑 1 相對路徑 2 絕對路徑 例如 1 相對路徑 和.c檔案在同一檔案目錄下,可直接寫檔名稱.檔案型別 fopen text.txt w 2 絕對路徑 fopen d studyfile te...
C 筆記 檔案操作
程式執行時產生的資料都屬於臨時資料,程式一旦執行結束都會被釋放 通過檔案可以將資料持久化 c 中對檔案操作需要包含標頭檔案 include 檔案型別分為兩種 二進位制檔案 檔案以文字的二進位制形式儲存在計算機中,使用者一般不能直接讀懂 檔案的操作 ofstream 寫操作 ifstream 讀操作 ...