一 对llseek做了不同的分析:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUF_SIZE 50
#define DEVICE_FILE "test.c"
int main(int argc, char *argv[])
{
int fd;
int num;
char buf[BUF_SIZE];
fd = open(DEVICE_FILE, O_RDWR);
if(fd < 0)
{
printf("open scull error!\n");
return -1;
}
memset(buf, 0, BUF_SIZE);
num = read(fd, buf, BUF_SIZE);
buf[num] = 0;
printf("%s\n", buf);
lseek(fd, 2, SEEK_SET);
write(fd, "aa", 2);
num = read(fd, buf, BUF_SIZE);
buf[num] = 0;
printf("%s\n", buf);
lseek(fd, 2, SEEK_SET);
num = read(fd, buf, BUF_SIZE);
buf[num] = 0;
printf("%s\n", buf);
lseek(fd, 0, SEEK_SET);
lseek(fd, 2, SEEK_CUR);
num = read(fd, buf, BUF_SIZE);
buf[num] = 0;
printf("%s\n", buf);
lseek(fd, 0, SEEK_SET);
lseek(fd, 0, SEEK_END);
memset(buf, 0, BUF_SIZE);
printf("read return value is %d.\n", read(fd, buf, BUF_SIZE));
return 0;
}
得出的打印结果:
2 代码:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUF_SIZE 50
#define DEVICE_FILE "test.c"
int main(int argc, char *argv[])
{
int fd;
int num;
char buf[BUF_SIZE];
fd = open(DEVICE_FILE, O_RDWR);
if(fd < 0)
{
printf("open scull error!\n");
return -1;
}
memset(buf, 0, BUF_SIZE);
num = read(fd, buf, BUF_SIZE);
buf[num] = 0;
printf("%s\n", buf);
lseek(fd, 2, SEEK_SET);
/* write(fd, "aa", 2); */
num = read(fd, buf, BUF_SIZE);
buf[num] = 0;
printf("%s\n", buf);
write(fd,"aa",2);
lseek(fd, 2, SEEK_SET);
num = read(fd, buf, BUF_SIZE);
buf[num] = 0;
printf("%s\n", buf);
lseek(fd, 0, SEEK_SET);
lseek(fd, 2, SEEK_CUR);
num = read(fd, buf, BUF_SIZE);
buf[num] = 0;
printf("%s\n", buf);
lseek(fd, 0, SEEK_SET);
lseek(fd, 0, SEEK_END);
memset(buf, 0, BUF_SIZE);
printf("read return value is %d.\n", read(fd, buf, BUF_SIZE));
return 0;
}
运行结果: