分享

read,write和lseek函数

 乾坤殿 2013-12-03
函数作用:
read函数是用于从指定文件描述符中读出数据。当从终端设备文件中读出数据时,通常一次最多读一行。
write函数是用于向打开的文件写数据,写操作从当前位移量开始。若磁盘写满或者超出该文件长度,则write返回失败。
lseek函数是用于在指定的文件描述符中将指针定位到相应的位置。

函数格式:
1.read函数
所需头文件:#include<unistd.h> /*是linux/unix的系统调用,包含了许多UNIX系统服务的 函数原型。*/

函数原型: ssize_t read(int fd, void *buf, size_t count)

fd: 文件描述符
buf指定存储器读出数据的缓存区
count指定读出的字节数。

返回值:成功:读到的字节数。 
             0:已到文件尾。
           -1:失败。
注意:在读普通文件时,若在要读相应的字节数之前就已经达到了文件尾,则返回的字节数小于count值。

2.write函数
所需头文件:#include<unistd.h>

函数原型:ssize_t write(int fd, void *buf, size_t count)

fd:文件描述符
buf:指定存储器写入数据的缓冲区
count:需要写入字节数。

返回值:成功:已写字节数
          失败:-1

3.lseek函数
所需头文件:#include<unistd.h>
                    #include<sys/types.h> /*定义了off_t,pid_t等类型*/

函数原型: off_t lseek(int fd,,off_t offset,int whence)

fd:文件描述符
offset:偏移量,该值可正可负,正值为向后移,负值为向前移

whence:有三个参数。
    (1).SEEK_SET: 当前位置为文件的开头,新位置为偏移量大小
    (2).SEEK_CUR: 当前位置为文件指针位置,新位置为当前位置加上偏移量大小
    (3).SEEK_END: 当前位置为文件结尾,新位置为偏移量大小

返回值成功:文件当前位移量
        失败:-1


举例:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAXSIZE
int main(void)
{
    int i,fd,size,len;
    char *buf="Hello! I'm writing to this file!";
    char buf_r[10];
    len = strlen(buf);
    buf_r[10] = '\0';
    if((fd = open("/tmp/hello.c", O_CREAT | O_TRUNC | O_RDWR,0666 ))<0)/*打开文件*/
    {
        perror("open:");
        exit(1);
    }
    else
        printf("open file:hello.c %d\n",fd);

    if((size = write( fd, buf, len)) < 0)/*写入数据*/
    {
        perror("write:");
        exit(1);
    }
    else
        printf("Write:%s\n",buf);

    lseek( fd, 0, SEEK_SET ); /*将指针定为文件开头,偏移量为0*/
    if((size = read( fd, buf_r, 10))<0)/*读入刚才所写数据*/
   {
        perror("read:");
        exit(1);
    }
    else
        printf("read form file:%s\n",buf_r);
    if( close(fd) < 0 )/*关闭文件*/
    {
        perror("close:");
        exit(1);
    }
    else
        printf("Close hello.c\n");
    exit(0);
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多