-
read()
鎖定
read( ),是一個計算機編程語言函數,功能為讀取文件內容,成功返回讀取的字節數。
- 函數名
- read
- 功 能
- 讀取文件內容
read()Linux C
read()函數定義
#include <unistd.h>
read()返回值
成功返回讀取的字節數,出錯返回-1並設置errno,如果在調read之前已到達文件末尾,則這次read返回0。
read()參數
參數count是請求讀取的字節數,讀上來的數據保存在緩衝區buf中,同時文件的當前讀寫位置向後移。注意這個讀寫位置和使用C標準I/O庫時的讀寫位置有可能不同,這個讀寫位置是記在內核中的,而使用C標準I/O庫時的讀寫位置是用户空間I/O緩衝區中的位置。比如用fgetc讀一個字節,fgetc有可能從內核中預讀1024個字節到I/O緩衝區中,再返回第一個字節,這時該文件在內核中記錄的讀寫位置是1024,而在FILE結構體中記錄的讀寫位置是1。注意返回值類型是ssize_t,表示有符號的size_t,這樣既可以返回正的字節數、0(表示到達文件末尾)也可以返回負值-1(表示出錯)。
read函數返回時,返回值説明了buf中前多少個字節是剛讀上來的。有些情況下,實際讀到的字節數(返回值)會小於請求讀的字節數count,例如:讀常規文件時,在讀到count個字節之前已到達文件末尾。例如,距文件末尾還有30個字節而請求讀100個字節,則read返回30,下次read將返回0
#include <stdio.h> #include <io.h> #include <alloc.h> #include <fcntl.h> #include <process.h> #include <sys/stat.h> int main(void) { void* buf ; int handle; int bytes ; buf=malloc(10); /* Looks for a file in the current directory named TEST.$$$ and attempts to read 10 bytes from it.To use this example you should create the file TEST.$$$ */ handle=open("TEST.$$$",O_RDONLY|O_BINARY,S_IWRITE|S_IREAD); if(handle==-1) { printf("ErrorOpeningFile\n"); exit(1); } bytes=read(handle,buf,10); if(bytes==-1) { printf("ReadFailed.\n"); exit(1); } else { printf("Read:%dbytesread.\n",bytes); } return0 ; }
read()相關函數
open,close,lseek,read,write。
read()Python
read()基本信息
read()基本語法
file.read([size])
read()參數説明
file:打開的文件對象。
size:可選參數,用於指定讀取字符個數,如果省略,則讀取所有內容。
read()程序示例
with open('message.txt','r') as file: #打開文件 string = file.read(9) #讀取前9個字符 print(string)
read()相關函數
open,close,readline,write,seek.
- 參考資料
-
- 1. 深入理解linux下write()和read()函數 .CSDN[引用日期2020-04-08]
- 2. Python File read() 方法 .RUNOOB[引用日期2020-04-08]