【文件I/O】——read & write

read

所需头文件

#include <unistd.h>

函数原型

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

read 函数从文件描述符(fd)所指代的已打开的文件中的当前偏移量处读取数据,一次最多读取 count 个字节,如果读取成功,则返回已经读到的字节数;如果遇到文件结束(EOF),则返回 0,如果出错就返回 -1。buf 是用来存放读取到的数据的内存缓冲区地址,该缓冲区至少应该有 count 个字节。

读取成功时,返回实际读到的字节数,这个有可能比 count 小。如:一次性请求读取的字节数(count)太大,而文件中的字节数不够时,或者快要读到文件末尾,所剩的字节数不够 count 个时。

这里说的遇到文件结束就返回 0 ,实际上是读完文件后,再一次读文件,就会返回 0 。如 “helloworld!” 这个 C 字符串一共有 12 个字节,假如每次读取 5 个字节,那么第三次会读到 2 个字节,第四次才是所谓的遇到文件末尾,然后返回 0 。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{ 
    int fd = -1;
    ssize_t nbytes = 0;
    char buf[32] = {0};                                                
    //打开文件    
    if ((fd = open("readcount.txt", O_RDONLY)) < 0)
    {             
        perror("open readcount.txt is faild");
    }             
    /*打印读取到的字节数*/
    do            
    {             
        nbytes = read(fd, buf, 5);
        printf("count is: %ld\n",nbytes);
    }while(nbytes != 0);
                  
    close(fd);    
    return 0;     
}
View Code
$ cat readcount.txt 
helloworld!
$ ls -l readcount.txt 
-rw-rw-r-- 1 shelmean shelmean 12 Jul 31 22:03 readcount.txt
$ ./a.out 
count is: 5
count is: 5
count is: 2
count is: 0

write

 所需头文件

#include <unistd.h>

函数原型

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

continue。。。

猜你喜欢

转载自www.cnblogs.com/shelmean/p/9395334.html
今日推荐