1.光标定位 lseek()函数
1.1函数需包含的头文件:
#include <sys/types.h>
#include <unistd.h>
1.2参数说明
fd:文件描述符
offset:偏移量
whence:位置
SEEK_SET:The offset is set to offset bytes. offset为0时表示文件开始位置。
SEEK_CUR:The offset is set to its current location plus offset bytes. offset为0时表示当前位置。
SEEK_END:The offset is set to the size of the file plus offset bytes. offset为0时表示结尾位置
函数返回值
成功返回当前位置到开始的长度
失败返回-1并设置errno
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define BUF_MAX 512 /*buf缓冲区最大值*/
/*向中文件写入数据并把写入内容打印到标准输出*/
int main(int argc, char* argv[])
{
if(argc < 2)
{
printf("not fount file name");
return -1;
}
int fd = open(argv[1], O_RDWR | O_CREAT);
write(fd, "hello linux...", 15);
/*读写位置在末尾*/
/*把读写位置移动到文件首部*/
lseek(fd, 0, SEEK_SET);
char buf[20];
memset(buf, 0, sizeof(buf));
int read_size = read(fd, buf, sizeof(buf));
if(read_size > 0)
{
write(STDOUT_FILENO, buf, read_size); /*STDIN_FILENO STDERR_FILENO*/
}
close(fd);
return 0;
}
2.关闭 文件close()函数
函数原型:
int close(int fd);
功能描述:用于关闭一个被打开的的文件
所需头文件: #include
函数原型:int close(int fd)
参数:fd文件描述符
函数返回值:0成功,-1出错