文件IO编程

  • 打开文件:

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

int open(const char *pathname,int flags);

int open(const char *pathname,int flags,mode_t mode);mode代表权限

int creat(const char *pathname,mode_t mode);

flag标记:

O_RDONLY:表示只读

O_WRONLY:只写

O_RDWR:可读写

O_APPEND:在内容末尾追加

O_TRUNC:删除原始数据,创建新数据

  • 文件读写:

#include <unistd.h>

ssize_t read(int fd,void *buf,size_t count);fd是文件描述符

ssize_t write(int fd,const void *buf,size_t count);

  • 控制文件读写位置:

#include <sys/types.h>

#include <unistd.h>

off_t lseek(int fd,off_t offset,int whence);

offset:偏移量,每次读写操作所需要移动的距离,单位是字节,可正可负(向前移,向后移)

whence:当前位置的基点;

SEEK_SET:当前位置为文件的开头,新位置为偏移量的大小

SEEK_CUR:当前位置为文件指针的位置,新位置为当前位置加上偏移量

SEEK_END:当前位置为文件结尾,新位置为文件大小

  • fcntl函数:

#include <unistd.h>

#include <fcntl.h>

int fcntl(int fd,int cmd);

int fcntl(int fd,int cmd,long arg);

int fcntl(int fd,int cmd,struct flock* lock);

  • 标准IO编程(带缓存区的IO编程):

打开文件:

   #include <stdio.h>

FILE *fopen(const char *path,const char *mode);

FILE *fdopen(int fd,const char *mode);

FILE *freopen(const char *path,const char *mode,FILE *stream);

mode取值:

r:打开只读文件,文件必须存在;

r+:打开可读写文件,文件必须存在;

w:打开只写文件,文件存在擦写新内容,不存在新建;

w+:打开可读写文件,。。。

a:以附加方式打开只写文件

a+:以附加的方式打开可读写文件

文件读写:

#include <stdio.h>

size_t fread(void *ptr,size_t size,size_t nmemb,FILE *stream);

size_t fwrite(const void *ptr,size_t size,size_t nmemb,FILE *stream);

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值