字符的输入
读取字符.PNG
字符输出
输出字符.PNG
使用getc和putc函数拷贝文件
//使用getc和putc函数拷贝文件
#include <stdio.h>
int main(int argc,char** argv[])
{
//打开文件获取文件描述符
FILE *fd1,*fd2;
fd1 = fopen("./1.txt","r");
fd2 = fopen("./2.txt","w");
if(fd1 == NULL)
{
perror("打开1.txt文件失败!");
}
if(fd2 == NULL)
{
perror("打开2.txt文件失败!");
}
while(1){
//循环获取文件中的字符的ASCII值
int c;
c = getc(fd1);
//如果获取字符失败则退出
if(c == EOF){
break;
}else{
putc(c,fd2);
}
}
//关闭文件
fclose(fd1);
fclose(fd2);
}
使用fgets和fputs拷贝文件
//使用fgets和fputs拷贝文件
#include <stdio.h>
int main(int argc,char** argv[])
{
//打开文件获取文件描述符
FILE *fd1,*fd2;
fd1 = fopen("./1.txt","r");
fd2 = fopen("./2.txt","w");
if(fd1 == NULL)
{
perror("打开1.txt文件失败!");
}
if(fd2 == NULL)
{
perror("打开2.txt文件失败!");
}
while(1){
//循环获取文件中的字符的ASCII值
char *len; // 用来获取取fgets函数的返回值,从而判断是否读取到文件末尾
char buf[10]; //开辟一个字符数组,用来存放每次读到的字符
len = fgets(buf,10,fd1); //将从fd1中读取10个字符,存放到buf中
//如果获取字符为空则退出
if(len == NULL){
break;
}else{
fputs(buf,fd2); //将buf中的数据写入到fd2中
}
}
//关闭文件
fclose(fd1);
fclose(fd2);
}