12,POSIX文件操作

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值