linux的常用操作——read函数和write函数
生活随笔
收集整理的這篇文章主要介紹了
linux的常用操作——read函数和write函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 read函數
\qquad返回值:-1:讀取失敗;0:表示文件讀完;>0:讀取的字節數
\qquad參數:第一個參數:要讀取文件的文件描述符;第二個參數:存取的地址;第三個參數:存取的字節數大小
2 write函數
\qquad返回值:-1:寫入失敗;字節數返回:寫入成功。
\qquad參數:第一個參數:要寫入文件的文件描述符;第二個參數:地址,從這個地址寫入到文件;第三個參數:空間大小
3 舉例
#include<stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<errno.h> #include<stdlib.h> #include<unistd.h>int main() {int open_h1_fd;int open_h2_fd;int close_h1_fd;int close_h2_fd;int read_fd;int write_fd;char buf[2048]={0};//1.打開h1.txt 和 h2.txtxopen_h1_fd = open("h1.txt",O_RDONLY);if(open_h1_fd==-1){perror("h1 open fail");exit(1);}open_h2_fd = open("h2.txt",O_WRONLY);if(open_h2_fd==-1){perror("h2 open fail");exit(1);}//2.讀取h1.txt的內容read_fd = read(open_h1_fd,buf,sizeof(buf));if(read_fd==-1){perror("read fail");exit(1);}//3.將讀取的內容寫入h2.txtwrite_fd = write(open_h2_fd,buf,sizeof(buf));if(write_fd==-1){perror("write fail");exit(1);}else{printf("write success!\n");}//4.關閉 h1.txt 和 h2.txtclose_h1_fd = close(open_h1_fd);if(close_h1_fd==-1){perror("h1 close fail");exit(1);}else if(close_h1_fd==0){printf("h1 close success!\n");}close_h2_fd = close(open_h2_fd);if(close_h2_fd==-1){perror("h2 close fail");exit(1);}else if(close_h2_fd==0){printf("h2 close success!\n");}return 0; }總結
以上是生活随笔為你收集整理的linux的常用操作——read函数和write函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++11新特性以及std::threa
- 下一篇: linux的基础知识——进程组