read()會把參數fd所指的檔案傳送nbyte個位元組到buf指針所指的記憶體中。若參數nbyte為0,則read()不會有作用並返回0。返回值為實際讀取到的位元組數,如果返回0,表示已到達檔案尾或無可讀取的數據。錯誤返回-1,並將根據不同的錯誤原因適當的設定錯誤碼。
基本介紹
- 函式名:read
- 功 能:從檔案中讀
- 函式原型:int read
- 表頭檔案:include <unistd.h>
程式例
#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 ;}