標準IO
頭文件需求:
#include <stdio.h>
1.fopen和fclose
(1)fopen
fopen的函數功能是打開一個文件。
首先看看fopen的函數聲明:
FILE *fopen(const char *path, const char *mode);
第一個參數path是文件地址,傳入的是不可變的字符串;第二個參數是mode是指打開方式,傳入的也是不可變的字符串;返回的是FILE指針。
mode的可選項主要有:
"r" Open text file for reading. The stream is positioned at the beginning of the file.
"r+" Open for reading and writing. The stream is positioned at the beginning of the file.
"w" Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
"w+" Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
"a" Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
"a+" Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.
(2)fclose
fclose的函數功能是關閉一個文件。
fclose的函數聲明:
int fclose(FILE *fp);
傳入的參數是FILE指針,即fopen創建的那個指針;成功則返回0,否則返回EOF,并將錯誤存儲在errno中
附:Linux中系統調用的錯誤都存儲于 errno中,errno由操作系統維護,存儲就近發生的錯誤,即下一次的錯誤碼會覆蓋掉上一次的錯誤。
2.fgetc和fputc
(1)fgetc
fgetc的功能是從stream中讀取下一個character。
函數聲明如下:
int fgetc(FILE *stream);
傳入的參數是stream來源即FILE指針。
(2)fputc
fputc的功能是將一個character寫入到stream中。
函數原型是:
int fputc(int c, FILE *stream);
?第一個參數就是要寫入的字符,雖然是int型,但是只用低八位(unsigned char);第二個參數即寫入到的stream來源即FILE指針。
int main(int argc, char const *argv[])
{FILE *fp1 = fopen("1.txt", "r");FILE *fp2 = fopen("2.txt", "w");if(NULL == fp1){fprintf(stderr, "fp1 open error");}while(1){int a = fgetc(fp1);if(EOF == a){break;}fputc(a, fp2);}fclose(fp1);fclose(fp2);return 0;
}
3.fgets和fputs
(1)fgets
fgets的功能是從stream中讀取至多一定數量的字符,并且存入buffer中,遇到'\n'或者EOF就停止讀取。
函數聲明:
char *fgets(char *s, int size, FILE *stream);
第一個參數是字符串buffer指針,傳入的是char*,這里當然是可變的;第二個參數是至多讀取的字符數,傳入的是int;第三個參數就是stream來源即FILE指針。
這個函數把獲取到的字符傳入buffer后,還會自動在末尾加上'\0'表示字符串的結束。
(2)fputs
fputs的功能是將字符串s傳到stream中。
函數聲明是:
int fputs(const char *s, FILE *stream);
第一個參數是不可變的字符串,第二個參數就是要寫到的stream來源這里是FILE指針。
字符串被寫入stream后,還會自動在末尾加上'\0'表示結束。
(3)fgets與fputs綜合運用復現copy
int main(int argc, char const *argv[])
{FILE *fp1 = fopen("5.txt", "r");FILE *fp2 = fopen("6.txt", "w");if(NULL == fp1 || NULL == fp2){fprintf(stderr, "fopen error");return 1;}while(1){char s[1024] = {0};if(NULL == fgets(s, sizeof(s), fp1)){break;}fputs(s, fp2);}return 0;
}
但是該函數不能拷貝二進制類型文件。?
?