标准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;
}
但是该函数不能拷贝二进制类型文件。