底层文件访问
文件描述符:
0:标准输入
1:标准输出
2:标准错误
write系统调用
把缓冲区buf的前nbytes个字节写入与文件描述符fildes关联的文件中。返回实际写入的字节数。返回0表示未写入,返回-1表示错误。
#include <unistd.h>
size_t write(int fildes,const void *buf,size_t nbytes)
#include<unistd.h> #include<stdlib.h> int main(){ if((write(1,"Here is some data\n",18))!=18) write(2,"A write error has occured on file desciptor 1 \n",46); exit(0); }
输出:
[email protected]:~/linux_program/CH03$ ./write Here is some data
read系统调用
从与文件描述符fileds相关联的文件里读入nbytes个字节的数据,并放在buffer中,返回实际读入的字节数。返回0表示未读入,-1表示错误。
#include <unistd.h>
size_t read(int fildes, void *buf,size_t nbytes)
#include<unistd.h> #include<stdlib.h> int main(){ char buffer[128]; int nread; nread = read(0,buffer,128); if(nread == -1) write(2,"A read error has occurred\n",26); if((write(1,buffer,nread)) != nread) write(2,"A write error has occurred\n",27); exit(0); }
输出:
[email protected]:~/linux_program/CH03$ echo hello world | ./read hello world
open系统的调用
为了创建一个新的文件描述符,需要使用open
#inlcude <fcntl.h>
int open(const char *path,int oflags);
int open(const char *path,int oflags,mode_t mode);
时间: 2024-12-30 04:30:55