dup
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main1()
{
int fd = open("test", O_WRONLY|O_CREAT, 0766);
if (-1 == fd)
{
perror("打开tmp.txt文件失败");
return -1;
}
int newfd = open("test", O_WRONLY|O_CREAT, 0766);
if (-1 == newfd)
{
perror("打开tmp.txt文件失败");
return -1;
}
newfd = dup(fd); //同步偏移量,此时newfd的偏移量等同fd
printf ("fd = %d\n", fd);
printf ("newfd = %d\n", newfd);
write(fd, "hello", 5);
write(newfd, "world", 5); //此时test显示为helloworld
close(fd);
return 0;
}
int main()
{
int fd = open("test", O_WRONLY|O_CREAT, 0766);
if (-1 == fd)
{
perror("打开tmp.txt文件失败");
return -1;
}
int newfd = open("test1", O_WRONLY|O_CREAT, 0766);
if (-1 == newfd)
{
perror("打开tmp.txt文件失败");
return -1;
}
// 将文件描述符表中指针部分 复制一份给 newfd
// 如果复制成功,则会将 原来 newfd 打开的文件关闭
dup2(fd, newfd);
printf ("fd = %d\n", fd); //fd 和 newfd 的值时不同的
printf ("newfd = %d\n", newfd);
write(fd, "hello", 5);
write(newfd, "world", 5); //test显示为helloworld
close(fd);
return 0;
}
lseek
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define SIZE 1024*1024*40
int main1()
{
int fd = open("1.ppt", O_RDONLY);
if (-1 == fd)
{
perror("打开tmp.txt文件失败");
return -1;
}
// 获取文件大小
off_t ret = lseek(fd, 0, SEEK_END);
printf ("文件大小:%ld\n", ret);
close(fd);
return 0;
}
int main2()
{
int fd = open("tmp.txt", O_WRONLY|O_CREAT |O_TRUNC, 0766);
if (-1 == fd)
{
perror("打开tmp.txt文件失败");
return -1;
}
write(fd, "hello", 5);
off_t ret = lseek(fd, 3, SEEK_SET);
write(fd, "world", 5);
close(fd);
return 0;
}
// 创建大文件
int main3()
{
int fd = open("big", O_WRONLY|O_CREAT, 0766);
if (-1 == fd)
{
perror("打开tmp.txt文件失败");
return -1;
}
off_t ret = lseek(fd, SIZE-1, SEEK_SET);
write(fd, "a", 1);
printf ("ret:%ld\n", ret);
close(fd);
return 0;
}
// 创建大文件
int main()
{
truncate("aa.txt", SIZE);
return 0;
}