Linux系统下文件的拷贝/复制——fgetc/fputc、fgets/fputs、fread/fwrite、read/write的用法

一、fgetc/fpuc

提前创建a.txt文件输入"hello world"

利用fputc和fgetc拷贝文件a.txt("r"表示读)

#include <stdio.h>
int main(int argc, char const *argv[])
{
    FILE *fp = NULL;
    FILE *tp = NULL;
    char ch ={0};
    fp =fopen("a.txt","r");
    tp = fopen("b.txt","w");
    if(NULL == fp || NULL ==tp )
    {
        perror("fail to open");
        return  -1;
    }
    while(1)
    {
        ch = getc(fp);
        if ( EOF == ch)
        {
            break;
        }
        putc(ch,tp);
    }
    fclose(fp);
    fclose(tp);
    return 0;
}

用"w"写读的方式获得b.txt

二、fgets/fpus

提前创建a.txt文件输入"how are you I am fine"

#include <stdio.h>
int main(int argc, char const *argv[])
{
    FILE *fp = NULL;
    FILE *tp = NULL;
    char ch[32] = {0};
    char *p = NULL;
    fp = fopen("a.txt","r");
    tp = fopen("c.txt","w");
    if( NULL== fp || NULL == tp)
    {
        perror("fail to open");
        return -1;
    }
    while(1)
    {
       p  = fgets(ch,sizeof(ch),fp);
        if(NULL == p)
        {
            break;
        }
        fputs(p,tp);
    }
    fclose(fp);
    fclose(tp);
    return 0;
}

用"w"写读的方式获得c.txt

三、fread/fwrite

提前创建a.txt文件输入"what are you do"

利用fread和fwrite拷贝文件a.txt("r"表示读)

#include <stdio.h>
int main(int argc, char const *argv[])
{
    FILE *fp = NULL;
    FILE *tp = NULL;
    char ch[32]={0};
    size_t x = 0 ;
    fp =fopen ("a.txt","r");
    tp = fopen("d.txt","w");
    if( NULL == fp || NULL == tp)
    {
        perror("fail to open");
        return  -1 ;
    }
    while(1)
    {
        x = fread(ch,1,sizeof(ch),fp);
        if( 0 == x)
        {
            break;
        }
        fwrite(ch,1,x,tp);
    }
    fclose(fp);
    fclose(tp);
    return 0;
}

用"w"写读的方式获得d.txt

四、read/write

提前创建a.txt文件输入"nihaoya"

利用read和write拷贝文件a.txt("r"表示读)

#include <stdio.h>
#include <sys/types.h>
#include<sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char const *argv[])
{
    int fp = 0; int tp = 0;
    char ch[7] = {0};
    size_t x;
    fp = open("a.txt",O_RDONLY);
    tp = open("e.txt",O_WRONLY | O_CREAT | O_TRUNC,0664);
    if( -1 == fp || -1 == tp)
    {
        perror("fail to open");
        return -1 ;
    }
    while(1)
    {
       x = read(fp,ch,sizeof(ch));
        if( 0 == x )
        {
            break;
        }
        write(tp,ch,sizeof(ch));
    }
    close(tp);
    close(fp);
    return 0;
}

用"w"写读的方式获得e.txt

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值