博客地址:http://blog.csdn.net/muyang_ren
1、文件按字符复制
/*************************************************************************
> File Name: 1_size.c
> Author: 梁惠涌
> Addr:
> Created Time: 2015年04月12日 星期日 22时24分52秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
int main(){
char ch;
FILE *fp1,*fp2;
fp1 = fopen("1_size.c","r");
if(fp1 ==NULL){
perror("fopen :");
exit(-1);
}
fp2 = fopen("1.txt","w");
if(fp2 ==NULL){
perror("fopen :");
exit(-1);
}
while((ch=getc(fp1)) != EOF){
putc(ch,fp2);
putc(ch,stdout);
}
fclose(fp1);
fclose(fp2);
return 0;
}
2、文件按行复制
/*************************************************************************
> File Name: 2_line.c
> Author: 梁惠涌
> Addr:
> Created Time: 2015年04月12日 星期日 22时38分22秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define size 40
int main(){
char str[size];
FILE *fp1,*fp2;
fp1 = fopen("2_line.c","r");
if(fp1 ==NULL){
perror("fopen :");
exit(-1);
}
fp2 = fopen("2.txt","w");
if(fp2 ==NULL){
perror("fopen :");
exit(-1);
}
while(fgets(str,size,fp1) != NULL){
fputs(str,fp2);
fputs(str,stdout);
}
fclose(fp1);
fclose(fp2);
return 0;
}
3、文件 【 直接IO 】复制
/*************************************************************************
> File Name: 3_direct.c
> Author: 梁惠涌
> Addr:
> Created Time: 2015年04月12日 星期日 22时47分08秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<strings.h>
#include<string.h>
#define size 100
int main(){
char str[size];
FILE *fp1,*fp2;
int flend_num;
fp1 = fopen("3_direct.c","r");
if(fp1 ==NULL){
perror("fopen :");
exit(-1);
}
fp2 = fopen("3.txt","w");
if(fp2 ==NULL){
perror("fopen :");
exit(-1);
}
fseek(fp1,0,SEEK_END); //定位文件指针到文件尾
flend_num = ftell(fp1); //flend_num存储文件字符总数
fseek(fp1,0,SEEK_SET); //定位文件指针到文件开始
while(ftell(fp1) < flend_num){
bzero(str,size);
fread(str,sizeof(str),1,fp1); //读取文件时,要使用sizeof,写满整个缓存空间
fwrite(str,strlen(str),1,fp2); //写入文件使用strlen,将缓存中的有效字符写入文件
fwrite(str,strlen(str),1,stdout);
}
fclose(fp1);
fclose(fp2);
return 0;
}
4、文件字符倒序复制
/*************************************************************************
> File Name: 4_reverse.c
> Author: 梁惠涌
> Addr:
> Created Time: 2015年04月16日 星期四 18时44分55秒
************************************************************************/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define size 100
int main(){
FILE *fp1,*fp2;
int file_len;
char str[size], ch;
printf("请输入字符串:");
scanf("%s", str);
fp1 = fopen("4_1.txt","w+r"); //正序文件
fp2 = fopen("4_2.txt","w"); //逆序文件
fwrite(str,strlen(str),1,fp1); //将输入字符串正序存入4_1.txt
fseek(fp1, 0, SEEK_END); //定位文件指针到文件尾
file_len = ftell(fp1);
for(; file_len>0; file_len--){
fseek(fp1, file_len-1, SEEK_SET);
ch=fgetc(fp1); //从该地址获取一个字符
fputc(ch, fp2);
fputc(ch, stdout);
}
putc('\n', stdout);
fclose(fp1);
fclose(fp2);
return 0;
}