#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(){
int fd = open("hello",O_RDWR|O_CREAT,0666);
write(fd,"helloworld\n",11);
char buf[50];
int cd = read(fd,buf,sizeof(buf));
if(cd){
write(STDOUT_FILENO,buf,sizeof(buf));
}
return 0;
}
执行后终端没有显示内容,因为文件的指针指向文件最后的位置,所以使用read()函数前要用lseek()函数重新设置文件指针的位置。
off_t lseek(int fd, off_t offset, int whence);
fd :文件描述符
offset:偏移量
whence:
SEEK_SET 文件开始的位置
SEEK_CUR 当前位置
SEEK_END 结尾
return :
成功:返回文件开始到当前的长度
失败:返回-1,设置errno
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(){
int fd = open("hello",O_RDWR|O_CREAT,0666);
write(fd,"helloworld\n",11);
lseek(fd,0,SEEK_SET);
char buf[50];
int cd = read(fd,buf,sizeof(buf));
if(cd){
write(STDOUT_FILENO,buf,sizeof(buf));
}
return 0;
}
成功显示字符