#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define MAXSIZE 1024
int main(int argc,char **argv)
{
int fp;
int ran_num,r_num,w_num,t_num;
char buf[MAXSIZE],head[MAXSIZE],tail[MAXSIZE];
struct stat f_stat;
if(argc!=2)
{
printf("Usage: ./fc filename \n");
exit(-1);
}
if(access(argv[1],F_OK)==0)
{ /* 检测文件是否已存在 */
printf("File %s existed !\n",argv[1]);
exit(-1);
}
if((fp=open(argv[1],O_WRONLY|O_CREAT,00644))==-1)
{ /* 创建文件 */
perror("Creat file");
exit(-1);
}
printf("Input some data:\n");
if((r_num=read(1,buf,MAXSIZE))<0)
{ /* 读数据到BUF中 */
perror("First Read");
exit(-1);
}
if((w_num=write(fp,buf,r_num))==-1)
{ /* 写如数据到文件中 */
perror("First Write");
exit(-1);
}
if(fstat(fp,&f_stat)==-1)
{ /* 获取文件信息 */
perror("Fstat error");
exit(-1);
}
printf("The file size is %d bytes\n",f_stat.st_size);
close(fp);
if((fp=open(argv[1],O_RDWR))==-1)
{ /* 创建文件 */
perror("Open file");
exit(-1);
}
/* 实现随机数 */
ran_num=random();
lseek(fp,ran_num%f_stat.st_size,SEEK_SET);
if((t_num=read(fp,tail,MAXSIZE))==-1)
{
perror("Tail error");
exit(-1);
}
lseek(fp,ran_num%f_stat.st_size,SEEK_SET);
bzero(buf,MAXSIZE);
if((r_num=read(1,buf,MAXSIZE))<0)
{ /* 读数据到BUF中 */
perror("Second Read");
exit(-1);
}
if((w_num=write(fp,buf,r_num-1))==-1)
{ /* 写如数据到文件中 */
perror("Second Write");
exit(-1);
}
if(write(fp,tail,t_num)==-1)
{ /* 写如数据到文件中 */
perror("TailWrite");
exit(-1);
}
lseek(fp,0,SEEK_SET);
if(read(fp,buf,MAXSIZE)==-1)
{
perror("Last Read");
exit(-1);
}
close(fp);
if(stat(argv[1],&f_stat)==-1)
{ /* 获取文件信息 */
perror("Fstat error");
exit(-1);
}
printf("The content of file is :\n%s",buf);
printf("The file size is %d bytes\n",f_stat.st_size);
return 0;
}
|