光标移动使用lseek函数:
1.lseek函数包含的头文件:
#include <sys/types.h>
#include <unistd.h>
2.lseek函数原型:
off_t lseek(int fd, off_t offset, int whence);
3.SEEK_SET:指向文件头部
4.SEEK_END:指向文件尾部
5.SEEK_CUR:指向文件当前位置
光标移到代码:
#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 = "zhongzifeng hen shuai !";
fd = open("./file1",O_RDWR); //打开当前路径的文件file1
if(fd == -1) //表示打开失败
{
printf("open file1 failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);//O_CREAT表示文件不存在时创>建文件
if(fd > 0)
{
printf("create file1 success !\n");
}
}
printf("open success file1 : fd = %d\n",fd);
//ssize_t write(int fd, const void *buf, size_t count);
int n_write = write(fd,buf,strlen(buf));
if(n_write != -1)
{
printf("write %d byte to file1\n",n_write);
}
//ssize_t read(int fd, void *buf, size_t count);
char* readBuf;
readBuf = (char *)malloc(sizeof(char)*n_write+1);
//off_t lseek(int fd, off_t offset, int whence);
lseek(fd,0,SEEK_SET);
//lseek(fd,-23,SEEK_CUR);
int n_read = read(fd,readBuf,n_write);
printf("read %d byte,context: %s\n",n_read,readBuf);
close(fd);
return 0;
}
运行的结果: