Chinaunix首页 | 论坛 | 博客
  • 博客访问: 516343
  • 博文数量: 118
  • 博客积分: 10028
  • 博客等级: 上将
  • 技术积分: 1820
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-07 18:46
文章分类

全部博文(118)

文章存档

2009年(12)

2008年(106)

我的朋友

分类: C/C++

2008-04-03 12:43:37


编写C程序完成:创建一个新文件,输入一段数据,然后随机移动指针接着插入一段数据。完成后,查看该文件的大小和内容。

#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;

}



结果:

zuii@zuii-desktop:~/c/sy$ ./fc hello
Input some data:
1111111111111111
The file size is 17 bytes
222222222222222222
The content of file is :
1111111111222222222222222222111111
The file size is 35 bytes

阅读(6749) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~