POSIX文件操作特点:
用户操作文件没有缓冲区,
用户操作文件没有记录的概念。
POSIX文件操作实例:
打开、关闭文件
向文件写入数据
从文件读出数据
读写指定长度的数据
在文件指定位置读写数据
实例源码:ANSI_file.c
//POSIX_file.c
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <unistd.h>
int main()
{
int fd;
int readnum;
int writenum;
char buff[128];
//打开文件
fd = open("./test.c", O_RDWR);
//打开失败
if(-1 == fd)
{
printf("open file error!\n");
return -1;
}
//读文件最后128字节数据
lseek(fd, -128, SEEK_END);
readnum = read(fd, buff, 127);
printf("%d bytes read!\n", readnum);
buff[readnum] = '\0';
printf("%s\n\n", buff);
//从文件开始处写数据
lseek(fd, 0, SEEK_SET);
strcpy(buff, "a string write by pfile!\n");
writenum = write(fd, buff, strlen(buff));
printf("%d bytes write!\n", writenum);
//关闭文件
close(fd);
return 0;
}