前言:
文件I/O可分为两类:第一类是非缓冲式的文件操作;该类型一般由系统调用,主要函数有open,write,read,lseek,close;第二类是缓冲式文件操作;该类型由标准输入输出提供操作;本文记录的是第一类文件I/O。
操作函数:
文件描述符
内核通过文件描述符打开的文件,它是一个非负整数。通常,文件描述符0对应标准输入;文件描述符1对应标准输出;文件描述符2对应标准出错。依照POSIX,这些整数应替换为符号常量 STDIN_FILENO 、 STDOUT_FILENO 、 STDERR_FILENO ,定义在 <unistd.h> 中。
/*
* this file is the operation about file descriptor.
* by chenhanzhun 2014.10.21
*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("print the fileno:\n");
printf("fileno of stdin =%d\n",fileno(stdin));
printf("fileno of stdout =%d\n",fileno(stdout));
printf("fileno of stderr =%d\n",fileno(stderr));
return 0;
}
open函数
/*
*函数功能:打开或创建一个文件;
*返回值:若打开成功返回文件描述符,若出错则返回-1;
*/
/*
*函数原型:
*/
#include <fcntl.h>
int open(const char* pathname, int oflag);
int open(const char* pathname, int oflags, mode_t mode);
/*
*参数解释:
*pathname是打开或创建的文件名称;
*oflag只能是下面三个中的一个或与其它选项组成:
*只能指定一个:O_RDONLY(只读),O_WRONLY(只写),O_RDWR(可读写)
*其它选项:
*O_APPEND :写操作追加到文件尾
*O_CREAT :若打开的文件不存在,则创建,需要使用第三个参数mode
*O_EXCL :测试文件是否存在,不存在则创建此文件
*O_TRUNC :若文件