5个不带缓存的文件I/O操作:open,read,write,lseek,close

不带缓存是指每一个函数都只调用系统中的一个函数,这些函数不是ANSIC的组成部分,是POSIX的组成部分。

#include <sys/types.h> // 提供类型 pid_t 的定义

#include <sys/stat.h>

#include <fcntl.h>

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

 

#include <unistd.h>

int close(int fd)

 

#include <unistd.h>

ssize_t read(int fd,void *buf,size_t count)

 

#include <unistd.h>

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

 

#include <unistd.h>

#include <sys/types.h>

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

 

牵涉到读写的成功就返回字节数,失败返回-1;其他的成功就返回0,失败返回-1.

 

指针必须显示初始化才能使用,如

char *buff;

read(fd,buff,10);

会发生段错误

 

#include<sys/types.h>

#include<stdlib.h> /*exit()*/

#include<unistd.h>

#include<fcntl.h>

#include<stdio.h>

 

int main()

{

int fd;

if((fd=open("test",O_RDWR,640))==-1){

perror("open");

exit(1);

}

printf("open file success!\n");

 

int num;

char *buff;

buff=calloc(sizeof(char),10);    //指针必须先初始化再使用,否则会了生段错误

if((num=read(fd,buff,10))==-1){

perror("read");

exit(1);

}

buff[10]='\0';

printf("read data from file:%s\n",buff);

 

if(lseek(fd,10,SEEK_SET)==-1){   // SEEK_SET表示文件开头

perror("seek");

exit(1);

}

printf("the file cursor goto 10\n");

 

if((num=write(fd,buff,5))==01){    //这里是写入,而不是插入,即它会把原文件的内容覆盖掉

perror("write");

exit(1);

}

printf("write success!\n");

 

close(fd);

exit(0);

}

相关文章:

  • 2021-05-27
  • 2021-11-29
  • 2022-12-23
  • 2021-12-05
  • 2021-11-27
  • 2022-02-26
猜你喜欢
  • 2021-05-11
  • 2021-05-21
  • 2022-12-23
  • 2021-09-15
  • 2021-08-19
  • 2021-10-10
  • 2021-07-18
相关资源
相似解决方案