最简单的文件操作

来源:互联网 发布:java语言袖珍 pdf 编辑:程序博客网 时间:2024/05/18 15:50

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

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

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

#include<sys/stat.h>

#include<fcntl.h>

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

 

#include<unistd.h>

intclose(int fd)

 

#include<unistd.h>

ssize_tread(int fd,void *buf,size_t count)

 

#include<unistd.h>

ssize_twrite(int fd,void *buf,size_t count)

 

#include<unistd.h>

#include<sys/types.h>

off_tlseek(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>

 

intmain()

{

intfd;

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

perror("open");

exit(1);

}

printf("openfile success!\n");

 

intnum;

char*buff;

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

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

perror("read");

exit(1);

}

buff[10]='\0';

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

 

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

perror("seek");

exit(1);

}

printf("thefile cursor goto 10\n");

 

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

perror("write");

exit(1);

}

printf("writesuccess!\n");

 

close(fd);

exit(0);

}

原创粉丝点击