原型
用于打开文件读取数据。
一旦有了与一个打开文件描述相连的文件描述符,只要该文件是用O_RDONLY或O_RDWR标志打开的,就可以用read()系统调用从该文件中读取字节。
在读取成功的时候,文件对应的读取位置指针,向后移动位置,大小为成功读取的字节数。
1 2 3 4 5 6 7 8
|
ssize_t read(int fd, void* buf, size_t count);
|
使用参考
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h>
int main(void) { int fd = -1, i; ssize_t size = -1; char buf[10]; char filename[] = "test.txt";
fd = open(filename, O_RDONLY); if(-1 == fd){ printf("open file %s failure, fd:%d\n", filename, fd); return -1; }
printf("open file %s success, fd:%d\n", filename, fd);
while(size){ size = read(fd, buf, 10); if(-1 == size){ close(fd); printf("read file error occurs\n");
return -1; } else { if(size > 0){ printf("read %d bytes:", size); printf("\"");
for(i = 0; i < size; ++i){ printf("%c", *(buf+i)); }
printf("\"\n"); } else { printf("reach the end of file\n"); } }
}
return 0; }
|