文件描述符的相关介绍可以去:
链接: https://blog.csdn.net/m0_52983689/article/details/113832017.
下面展示一些 内联代码片
。
off_t lseek(int fd,off_t offest,int whence)
fd:文件描述符
offest:对whence的一个偏移值
whence:
SEEK_SET 指向文件的头 SEEK_END 指向文件的尾 SEEK_CUR 文件的当前位置
返回值:成功返回0,失败返回-1,可以用perror()函数查看错误。
/**********************可以用来计算文件的大小**********************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf="You Matter!";
// int open(const char *pathname, int flags);
// int open(const char *pathname, int flags, mode_t mode);
fd = open("./file1",O_RDWR);
int filesize = lseek(fd,0,SEEK_END);
printf("The file size is %d byte\n",filesize);
close(fd);
return 0;
}
/********************可以用来移动光标,为读文件做准备********************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf="You Matter!";
char *readbuf;
fd = open("./file1",O_RDWR);
printf("fd = %d\n",fd);
if(fd == -1){
printf("open file error!\n");
fd=open("./file1",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("Creating a successful!\n");
}
}
printf("fd = %d\n",fd);
int n_write=write(fd,buf,strlen(buf));
if(n_write != -1){
printf("write %d byte content\n",n_write);
}else{
printf("write error!\n");
}
readbuf=(char *)malloc(sizeof(char)+1);
lseek(fd,0,SEEK_SET);
int n_read=read(fd,readbuf,n_write);
if(n_read!=-1){
printf("read %d byte,content is %s\n",n_read,readbuf);
}else{
printf("read error!\n");
}
close(fd);
return 0;
}