1.不带缓冲的文件IO/操作
主要有5个函数:open, read, write,lseek,close。这里的不带缓冲指的是每一个函数都只调用系统中的一个函数。
open()
是用于打开或创建文件,可以指定文件的属性及用户权限等参数。
所需头文件:<sys/types.h>,<sys/stat.h>,<fcntl.h>
函数原型: int open(const char *pathname, flags, int perms);
pathname:被打开的文件名(可包含路径);
flags:文件的打开方式
O_RDONLY:只读方式打开文件;
O_WRONLY:可写方式打开文件;
O_RDWR:读写方式打开文件;
O_CREAT:如果文件不存在就创一个的新文件,并用第三个参数设置文件的权限;
O_EXCL:如果使用O_CREAT时文件已存在,则可返回错误消息。这一参数可测试文件是否已存在;
O_NOCTTY:如文件为终端,那么终端不可以作为调用open系统调用的那个进程的控制终端;
O_TRUNC:如果文件已存在,并且以只读或只写成功打开,那么会先全部删除文件中原有数据;
O_APPEND:以追加方式打开文件,打开文件的同时,文件指针指向文件结尾;
perms:被打开文件的权限,为8进制表示法; 如0755,0644, 0666;
close()
用于关闭一个打开的文件,当一个进程终目时,它所有已打开的文件都由内核自动关闭。
所需头文件:<unistd.h>
函数原型:int close(int fd);
fd:文件描述符;
函数返回值: 0成功,-1失败;
read()
所需头文件:<unistd.h>
函数原型: ssize_t read(int fd, void *buf, size_t count)
fd:文件描述符;
buf:读出数据的缓冲区;
count:读出的字节数;
函数返回值:成功读取的字节数, 0已到达文件结尾, -1出错;
write()
所需头文件:<unistd.h>
函数原型:ssize_t write(int fd, void *buf, size_t count)
fd:文件描述符;
buf:要写入的数据缓冲区;
count:写入的字节数;
函数返回值:成功:已定入的字节数,-1失败;
lseek()
所需头文件:<unistd.h>, <sys/types.h>
函数原型:off_t lseek(int fd, off_t offset, int whence)
fd:文件描述符;
offset:偏移量,单位字节数量,可正负(正向后移动,负向前移动)
whence:当前位置基点
SEEK_SET:当前位置为文件开头,新位置为偏移量大小;
SEEK_CUR:当前位置为文件指针的位置,新位置为当前位置加上偏移量;
SEEK_END:当前位置为文件的结尾,新位置为文件的大小加上偏移量的大小;
函数返回值: 成功文件的当前位移;-1出错;
fileio.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
int i,fd,size,len;
char *path="./abc.conf";
char buf_r[32];
char buf_w[32];
for (i=0; i<argc; i++) {
printf("\033[0;31;40m""argv[%d]:%s\n""\033[0m",i , argv[i]);
}
printf("\n\n");
// open file O_CREAT , O_RDWR, O_TRUNC, O_RDONLY, O_RWONLY, O_APPEND,
if ((fd=open(path, O_CREAT | O_RDWR | O_APPEND, 0644)) < 0) {
perror("open:");
exit(1);
} else {
printf("open file:%s , fd:%d\n", path, fd);
}
size = lseek(fd, 0, SEEK_CUR);
printf("current :%d\n", size);
printf("\n\n");
// seek file SEEK_SET, SEEK_CUR, SEEK_END
if (size = lseek(fd, 0, SEEK_SET)) {
perror("seek");
} else {
printf("seek to %d\n", size);
}
printf("\n\n");
// write file
for (i=0; i < argc; i++) {
size = write(fd, argv[i], strlen(argv[i]));
if (size < 0) {
printf("write faild!\n");
} else {
printf("write:%d, %s\n", size, argv[i]);
}
}
size = lseek(fd, 0 , SEEK_CUR);
printf("current %d\n", size);
printf("\n\n");
size = lseek(fd, -10, SEEK_CUR);
printf("seek to %d\n", size);
// read file.
if ( (size = read(fd, buf_r, sizeof(buf_r))) < 0) {
printf("read file error!\n");
} else {
printf("read: %d, %s\n", size, buf_r);
}
printf("\n\n");
// close file
if ( close(fd) < 0) {
perror("close: ");
exit(1);
} else {
printf("close fd:%d\n", fd);
}
}