您的位置:首页 > 其它

1.实验 5.2.5 文件定位 用lseek()函数实现以下功能 1. 获取文件大小 2. 为文件添加指定长度的空洞 3. 在指定位置写入指定内容 4. 读出指定位置的内容 1. 获取文件大小

2017-07-14 23:11 1191 查看
1.实验 5.2.5 文件定位
用lseek()函数实现以下功能
1. 获取文件大小
2. 为文件添加指定长度的空洞
3. 在指定位置写入指定内容
4. 读出指定位置的内容
1. 获取文件大小
源代码:
#include <stdio.h>
#include <stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

int main(int argc,char  *argv[])
{
int fd,length;
if(argc<2)
{
puts("Please input the open file pathnane!");
exit(1);
}

if((fd=open(argv[1],O_RDONLY))<0)
{
perror("Open file failure!");
exit(1);
}

if((length = lseek(fd,0,SEEK_END))<0)
{
perror("lseek file failure!");
}

printf("The file's length is %d\n",length);
close(fd);
exit(0);
}
2. 为文件添加指定长度的空洞
源代码:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

#define ERR_EXIT(m)
int main(void)
{
int fd;
int ret;
fd = open("tesk.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
if(fd == -1)
ERR_EXIT("open error");
write(fd,"hello",5);
ret = lseek(fd, 4,SEEK_CUR);
if(ret == -1)
ERR_EXIT("lseek error");
write(fd,"world",5);
close(fd);
return 0;
}

3. 在指定位置写入指定内容
源代码:
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
char buf1[] = "1234567890";
char buf2[] = "ABCDEFGHIJ";

int main(int argc,char  *argv[])
{
int fd;
if ( (fd = creat("/tmp/test",0644 )) < 0)
{
perror("creat");
exit(EXIT_FAILURE);
}
if (write(fd, buf1, 10) != 10)
{
perror("write");
exit(EXIT_FAILURE);
}

if(lseek(fd, 10, SEEK_SET) == -1)//偏移
{
perror("lseek");
exit(EXIT_FAILURE);
}
if (write(fd, buf2, 10) != 10)
{
perror("write");
exit(EXIT_FAILURE);
}
return 0;
}

4. 读出指定位置的内容
源代码:
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE
int main(void)
{
int i,fd,size,len;
char *buf="Hello!hellohellohellohello";
char buf_r[10];
len = strlen(buf);
if((fd = open("/tmp/hello.c", O_CREAT | O_TRUNC | O_RDWR,0666 ))<0){
perror("open:");
exit(1);
}
else
printf("open file:hello.c %d\n",fd);
if((size = write( fd, buf, len)) < 0){
perror("write:");
exit(1);
}
else
printf("Write:%s\n",buf);
lseek(fd, 0, SEEK_SET );
if((size = read( fd, buf_r, 10))<0){
perror("read:");
exit(1);
}
else
printf("read form file:%s\n",buf_r);
if( close(fd) < 0 ){
perror("close:");
exit(1);
}
else
printf("Close hello.c\n");
exit(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐