函数read、write、lseek
生活随笔
收集整理的這篇文章主要介紹了
函数read、write、lseek
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
函數(shù)原型:?
#include<unistd.h> ssize_t read(int fd, void *buf, size_t count);返回值:讀到的字節(jié)數(shù),若已到文件尾,返回0;若出錯,返回-1參數(shù):
- fd:函數(shù)open的返回值
- buf:緩沖區(qū),存儲要讀取的數(shù)據(jù)
- count:緩沖區(qū)的最大字節(jié)數(shù)size(buf)
?
函數(shù)原型:
#include<unistd.h> sszie_t write(int fd, const void *buf, size_t count);返回值:若成功,返回已寫的字節(jié)數(shù),若出錯,返回-1參數(shù):
- fd:函數(shù)open返回值
- buf:要寫到文件的數(shù)據(jù)
- count:strlen(buf)
?
測試代碼:
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>int main(int argc, const char* argv[]) {int fd = open("english.txt", O_RDWR);printf(" fd = %d\n", fd);int fd1 = open("temp", O_WRONLY | O_CREAT, 0664);printf("fd1 = %d\n",fd1);char buf[4096];int len = read(fd, buf, sizeof(buf));while(len > 0) {int ret = write(fd1, buf, len);printf("ret = %d\n", ret);len = read(fd, buf, sizeof(buf));}close(fd);close(fd1);return 0; }輸出結(jié)果:
?
函數(shù)原型:
?
參數(shù):
- 若whence是SEEK_SET,則將該文件的偏移量設(shè)置為距文件的開始處offset個字節(jié)。
- 若whence是SEEK_CUR,則將該文件的偏移量設(shè)置為當(dāng)前值加offset,offset可正可負(fù)。
- 若whence是SEEK_END,則將該文件的偏移量設(shè)置為文件長度加offset,offset可正可負(fù)。
使用:
- 文件指針移動到頭部:lseek(fd, 0, SEEK_SET);
- 獲取文件指針當(dāng)前位置:int len = lseek(fd, 0, SEEK_CUR);
- 獲取文件長度:int len = lseek(fd, 0, SEEK_END);
- 文件拓展:文件原大小100k,拓展為1100k。lseek(fd, 1000, SEEK_END); 最后一次寫操作:write(fd, "a", 1);
?
測試代碼:
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <fcntl.h>int main(int argc, const char *argv[]) {int fd = open("english.txt", O_RDWR);if(fd == -1) {perror("open error");exit(1);}int len = lseek(fd, 1000, SEEK_END);printf("len = %d\n", len);write(fd, "a", 1);close(fd);return 0; }
輸出結(jié)果:
?
阻塞與非阻塞
阻塞和非阻塞是文件的屬性還是read函數(shù)的屬性? 答案:文件的屬性
- 普通文件:hello.c 不阻塞
- 終端設(shè)備:/dev/tty、管道、套接字:,默認(rèn)阻塞
?
1. 阻塞讀終端
測試代碼:
#include <stdio.h> #include <stdlib.h> #include <unistd.h>int main() {char buf[10];int n;n = read(STDIN_FILENO, buf, 10);if(n < 0) {perror("read STDIN_FILENO");exit(1);}write(STDOUT_FILENO, buf, n);return 0; }輸出結(jié)果:
分析:
?
測試代碼:
#include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #define MSG_TRY "try agin\n"int main() {char buf[10];int fd, n;// /dev/tty --->當(dāng)前打開的終端設(shè)備fd = open("/dev/tty", O_RDONLY | O_NONBLOCK);if(n < 0) {perror("open /dev/tty");exit(1);}tryagin:n = read(fd, buf, 10);if(n < 0) {//如果write為非阻塞,但是沒有數(shù)據(jù)可讀,此時全局變量errno被設(shè)置為EAGAINif(errno == EAGAIN) {sleep(3);write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));goto tryagin;}perror("read /dev/tty");exit(1);}write(STDOUT_FILENO, buf, n);close(fd);return 0; }輸出結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的函数read、write、lseek的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 创维电视好吗?好在哪?
- 下一篇: 最强男神剧情介绍