Linux 系統 IO之 read write 函數
文章目錄
1. read 函數
1.1 頭文件包含
// 記憶方法:unistd <--> uinx std
#include <unistd.h>
1.2 函數原型
// size_t:無符號整型
// ssize_t:有符號整型 <==> int
ssize_t read(int fd, void *buf, size_t count);
1.3 函數功能
read
函數從給定的文件描述符指定的文件中,讀取 count
個字節的數據,存放至 buf中。
1.4 函數返回值
- 返回
-1
:文件讀取失敗,設置errno
指出失敗原因 - 返回
0
:文件讀取結束 - 返回
>0
: 本次所成功讀取的字節數
1.5 形參解釋
int fd
:指定要讀寫的文件描述符void* buf
:緩衝區,一般是一個數組,用於存放讀取的內容size_t count
:一次要讀取的最大字節數
2. write 函數
2.1 頭文件包含
#include <unistd.h>
2.2 函數原型
ssize_t write(int fd, const void *buf, size_t count);
2.3 函數功能
write
函數將 buf
中的 count
字節數據寫入指定文件描述符的文件中。
2.4 函數返回值
- 返回
-1
:文件寫失敗,錯誤代碼存至errno
中 - 返回
0
:count
參數爲 0 時,返回 0 ,此時沒有寫入任何數據 - 返回
>0
: 本次所成功寫入文件的字節數
2.5 形參解釋
int fd
:指定要寫入的文件描述符void* buf
:緩衝區,一般是一個數組,讀取存放於該數組的內容存放於文件中size_t count
:要寫入的實際字節數
3. 案例程序:讀寫一個已存在文件內容至新建文件中
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int fd_rd = open("annNote", O_RDONLY);
if( -1 == fd_rd){
perror("open read file");
exit(1);
}
// 如果文件不存在,新建
// 如果文件存在,則截斷文件內容(清空)
int fd_wr = open("annWrite", O_RDWR | O_CREAT | O_TRUNC, 0777);
if(-1 == fd_wr){
perror("open write file");
exit(-1);
}
char buf[1024] = {0};
int readSize = -2;
int writeSize = -2;
while(1){
readSize = read(fd_rd, buf, 1024);
if(0 == readSize)
break;
if( -1 == readSize){
perror("read");
exit(-1);
}
// 一定要注意,第三個參數是要實際寫如文件的字節數
writeSize = write(fd_wr,buf, readSize);
if( -1 == writeSize){
perror("write");
exit(-1);
}
}
// 記得關閉打開的文件描述符
if(-1 == close(fd_rd)){
perror("close fd_rd");
exit(-1);
}
if(-1 == close(fd_wr)){
perror("close fd_wr");
exit(-1);
}
return 0;
}