打開函數 fopen 的原型如下。
FILE * fopen(char *filename, char *mode);
返回值:打開成功,返回該文件對應的 FILE 類型的指針;打開失敗,返回 NULL。
模式 | 含 義 | 說 明 |
---|---|---|
r | 只讀 | 文件必須存在,否則打開失敗 |
w | 只寫 | 若文件存在,則清除原文件內容后寫入;否則,新建文件后寫入 |
a | 追加只寫 | 若文件存在,則位置指針移到文件末尾,在文件尾部追加寫人,故該方式不 刪除原文件數據;若文件不存在,則打開失敗 |
r+ | 讀寫 | 文件必須存在。在只讀 r 的基礎上加 '+' 表示增加可寫的功能。下同 |
w+ | 讀寫 | 新建一個文件,先向該文件中寫人數據,然后可從該文件中讀取數據 |
a+ | 讀寫 | 在” a”模式的基礎上,增加可讀功能 |
rb | 二進制讀 | 功能同模式”r”,區別:b表示以二進制模式打開。下同 |
wb | 二進制寫 | 功能同模式“w”。二進制模式 |
ab | 二進制追加 | 功能同模式”a”。二進制模式 |
rb+ | 二進制讀寫 | 功能同模式"r+”。二進制模式 |
wb+ | 二進制讀寫 | 功能同模式”w+”。二進制模式 |
ab+ | 二進制讀寫 | 功能同模式”a+”。二進制模式 |
關閉函數 fclose 的原型如下。
int fclose(FILE *fp); // 函數參數:fp:已打開的文件指針。
返回值:正常關閉,返回否則返回 EOF(-1)。
文件格式化輸出函數 fprintf 的函數原型為:所在頭文件:<stdio.h>
int fprintf (文件指針,格式控制串,輸出表列);
函數功能:把輸出表列中的數據按照指定的格式輸出到文件中。
返回值:輸出成功,返回輸出的字符數;輸出失敗,返回一負數
#include <stdio.h> #define SUCCESS 1 #define FAIL 0 #define FILE_PARH "/root/Desktop/data/new/" #define FILE_NAME FILE_PARH "test.text" int writFile() { FILE *fp; fp = fopen(FILE_NAME, "w+"); if (!fp) { return FAIL; } fprintf(fp,"this is a test %s\n","- OK"); fclose(fp); return SUCCESS; } int main(int argc, char* argv[]) { int iRes = SUCCESS; iRes = writFile(); return iRes; } 運行結果: [root@192 new]# cat ./test.text this is a test - OK
C 語言程序中常使用 fseek 函數移動文件讀寫位置指針
int fseek(FI:LE *fp, long offset, int origin);
函數功能:把文件讀寫指針調整到從 origin 基點開始偏移 offset 處,即把文件讀寫指針移動到 origin+offset 處。
基准位置 origin 有三種常量取值:SEEK_SET、SEEK_CUR 和 SEEK_END,取值依次為 0,1,2。
SEEK_SET:文件開頭,即第一個有效數據的起始位置。
SEEK_CUR:當前位置。
SEEK_END:文件結尾,即最后一個有效數據之后的位置。
#include <stdio.h> #define SUCCESS 1 #define FAIL 0 #define FILE_PARH "/root/Desktop/data/new/" #define FILE_NAME FILE_PARH "a.text" int writeBeginFile() { int iRes = SUCCESS; FILE *fp; fp = fopen(FILE_NAME, "w+"); if (!fp) { return FAIL; } fprintf(fp,"this is a test content %s\n","- OK"); fprintf(fp,"this is a test content %s\n","- OK"); fseek(fp, 0, SEEK_SET); //文件頭 fprintf(fp, "%s\n", "This the file begin"); fseek(fp, 0, SEEK_END); //文件尾 fprintf(fp, "%s\n", "This the file end"); fclose(fp); return iRes; } int main(int argc, char* argv[]) { int iRes = SUCCESS; iRes = writeBeginFile(); return iRes; }
運行結果:
[root@192 new]# cat a.text
This the file begin
nt - OK
this is a test content - OK
This the file end