一、fgetc/fpuc
提前创建a.txt文件输入"hello world"
![](https://i-blog.csdnimg.cn/blog_migrate/f1d0798d14133cafb4094c3336f5e6d4.png)
利用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;
}
![](https://i-blog.csdnimg.cn/blog_migrate/01ba6e65a6d895a97680927adfb3a2dd.png)
用"w"写读的方式获得b.txt
![](https://i-blog.csdnimg.cn/blog_migrate/eb20231df0f3ca94d07a78fc7f9e06f3.png)
二、fgets/fpus
提前创建a.txt文件输入"how are you I am fine"
![](https://i-blog.csdnimg.cn/blog_migrate/8928da520c9610f3502d4908bc4cc577.png)
#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;
}
![](https://i-blog.csdnimg.cn/blog_migrate/85fb432a7105dc2533dc0409f07473a3.png)
用"w"写读的方式获得c.txt
![](https://i-blog.csdnimg.cn/blog_migrate/9ad01569fd909ce894db9abbe0680382.png)
三、fread/fwrite
提前创建a.txt文件输入"what are you do"
![](https://i-blog.csdnimg.cn/blog_migrate/6c20a8a9119040196b73034b3d65d406.png)
利用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;
}
![](https://i-blog.csdnimg.cn/blog_migrate/01e0dbb1cf897eafef5790b4e6fe6dba.png)
用"w"写读的方式获得d.txt
![](https://i-blog.csdnimg.cn/blog_migrate/d7c67e91d69b291c02437487a4c0e961.png)
四、read/write
提前创建a.txt文件输入"nihaoya"
![](https://i-blog.csdnimg.cn/blog_migrate/01e4df53b4753486817ec4ed1e5f9953.png)
利用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;
}
![](https://i-blog.csdnimg.cn/blog_migrate/cb5a50231ba6b873d13af4fad4861394.png)
用"w"写读的方式获得e.txt
![](https://i-blog.csdnimg.cn/blog_migrate/c37d58f7526556ef9ea9df0f4ba33ec6.png)