文件Io:用fread实现fgets和fgetc

#include <stdio.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
void my_fputc(char *pbuf,FILE *fp2,int start,FILE *fp)
{
    int ret,end;
    if(feof(fp))
    {
        end=ftell(fp);
        ret=fwrite(pbuf,end-start,1,fp2);
    }
    else
    ret=fwrite(pbuf,1,1,fp2);
    if(ret==0&&ferror(fp2))
        {
            printf("write operation failed!\n");
            return;
        }
}

void my_fgetc(char *pbuf,FILE * fp,FILE *fp2)
{
    int ret,start;
    while(1)
    {
        start=ftell(fp);
        memset(pbuf,0,1);
        ret=fread(pbuf,1,1,fp);
         if(ret==0&&ferror(fp))
        {
            printf("read operation failed!\n");
            return;
        }
         my_fputc(pbuf,fp2,start,fp);
         if(feof(fp))
         {
             printf("Finish\n");
             return;
         } 
    }
}
void my_fputs(char *pbuf,FILE *fp2,int count)
{
    fwrite(pbuf,count,1,fp2);
    return;
}
void my_fgets(char * pbuf,FILE *fp,FILE *fp2,int count)
{
    fread(pbuf,count,1,fp);
    my_fputs(pbuf,fp2,count);
    printf("finish\n");
    return;
}

int main(int argc, const char *argv[])
{
    int i;
    printf("The first file is the source,The second one is the destination:\n");
    FILE *fp=fopen(argv[1],"r+");
    if(NULL==fopen)
    {
        printf("The first file opening operation failed !\n");
        perror("The reason is :\n");
        return -1;
    }
    FILE *fp2=fopen(argv[2],"w+");
    if(NULL==fopen)
    {
        printf("The second file opening operation failed !\n");
        printf("The reason is %s\n",strerror(errno));
        return -1;
    }
    
    printf("Input 1 :getchar & putchar\nInput 2 : gets & puts\n");
    scanf("%d",&i);

    if(i==1)
            {
    char *pbuf=calloc(1,1);
    if(NULL==pbuf)
    {
        printf("The creation operation of the buffer area failed");
        return -1;
    }
    my_fgetc(pbuf,fp,fp2);
            }
    else
    {
        int end,start,count;
        start=ftell(fp);
        fseek(fp,0,SEEK_END);
        end=ftell(fp);
        fseek(fp,0,SEEK_SET);
        count=end-start;
        char *pbuf=calloc(1,count);
        my_fgets(pbuf,fp,fp2,count);
    }
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值