一、标准IO。
1、标准IO有什么特点?
系统IO专门用于访问硬件设备的,标准IO专门用于访问普通文件。
标准IO中所有函数都是属于标准C库中的接口,所以标准IO的函数都是属于man手册中第3手册。
2、如何使用标准IO访问文件?
1)访问文件? -> fopen() -> man 3 fopen
函数功能: stream open functions
头文件:#include <stdio.h>
原型:
FILE *fopen(const char *path, const char *mode);
参数:
path:需要打开的那个文件的路径 (绝对路径/相对路径)
mode:操作权限 -> 字符串 例如:"r"
r Open text file for reading. The stream is positioned at the beginning of the file.
//以只读的方式来打开文件,文件的定位在最开头的。
O_RDONLY
r+ Open for reading and writing. The stream is positioned at the beginning of the file.
//以可读可写的方式来打开文件,文件的定位在最开头的。
O_RDWR
w Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
//以只写的方式打开文件,如果文件不存在就创建该文件,如果文件存在,则清空文件的内容,文件的定位在最开头的。
O_WRONLY|O_CREAT|O_TRUNC
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.
//以可读可写的方式来打开文件,如果文件不存在就创建该文件,如果文件存在,则清空文件的内容,文件的定位在最开头的。
O_RDWR|O_CREAT|O_TRUNC
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.
//以只写追加的方式打开文件,写的话就在文件末尾开始写,文件不存在就会创建,文件的定位在末尾。
O_WRONLY|O_APPEND
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.
//以可读可写和追加的方式打开文件,写的话就在文件末尾开始写,文件不存在就会创建,如果读,就从文件开头读,如果写,就从文件末尾开始写。
O_RDWR|O_CREAT|O_APPEND
返回值:
成功:文件流指针 FILE *
失败:NULL
2)关闭文件。 -> fclose() -> man 3 fclose
函数功能: fclose - close a stream
头文件:#include <stdio.h>
原型:
int fclose(FILE *stream);
参数:
stream: 需要关闭的那个文件的文件指针
返回值:
成功:0
失败:EOF
#define EOF -1
练习1: 测试一下fopen()打开一个文件后,会不会占用一个文件描述符?
练习2: 打开一个文件,测试fopen第二个参数,并关闭文件。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
FILE *fp = NULL;
fp = fopen("./test.txt","w");
if(fp == NULL)
printf("fopen error!\n"); -> 3
int fd = open("./kk.txt",O_RDONLY);
print