示例:以字符为单位复制文件
复制文件a.txt,保存到b.txt中
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp1,*fp2;
char ch;
if((fp1=fopen("a.txt","r"))==NULL) /*打开用于复制的源文件*/
{
printf("Cannot open source file.\n");
exit(1);
}
if((fp2=fopen("b.txt","w+"))==NULL) /*打开用于写入的目标文件*/
{
printf("Cannot open traget file.\n");
exit(1);
}
while((ch=fgetc(fp1))!=EOF) /*从源文件中逐个地读出字符*/
fputc(ch,fp2); /*将读出的字符逐个写入到文件*/
fclose(fp1);
fclose(fp2);
return 0;
}
示例:以字符串为单位复制文本文件
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp1,*fp2;
char string[80]; /*定义字符数组,用于读入字符串*/
if((fp1=fopen("a.txt","r"))==NULL) /*打开用于复制的源文件*/
{
printf("Cannot open source file.\n");
exit(1);
}
if((fp2=fopen("b.txt","w+"))==NULL) /*打开用于写入的目标文件*/
{
printf("Cannot open traget file.\n");
exit(1);
}
fgets(string, 80, fp1); /*从源文件中读入字符串*/
while(!feof(fp1)) /*若未结束*/
{
fputs(string, fp2); /*将读入的字符串写入目标文件*/
fgets(string, 80, fp1); /*继续从源文件中读入字符串*/
}
fclose(fp1);
fclose(fp2);
return 0;
}
从键盘上输入数据,并保存到文件中:从键盘上输入3名同学的学号、姓名和成绩,将这些数据保存到文本文件student.dat中
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int number;
char name[11];
float score;
} Student;
int main( )
{
FILE* fpout;
if((fpout=fopen("student.dat","w"))==NULL) /*打开用于保存数据的文件*/
{
printf("Cannot open file.\n");
exit(1);
}
Student stu;
int i;
for(i=0; i<3; ++i) /*处理3位同学的成绩*/
{
scanf("%d %s %f", &stu.number, stu.name, &stu.score); /*输入数据*/
fprintf(fpout, "%d %s %5.1f\n", stu.number, stu.name, stu.score); /*写到文件中*/
}
fclose(fpout); /*关闭文件*/
return 0;
}
两个运行结果完全相同的程序
(1)
#include <stdio.h>
int main()
{
char name[20];
float score;
scanf("%s %f", name, &score); /*从键盘输入*/
printf("name: %s, score: %f\n", name, score); /*输出到显示器*/
return 0;
}
(2)
#include <stdio.h>
int main()
{
char name[20];
float score;
fscanf(stdin, "%s %f", name, &score); /*从标准输入设备读取数据*/
fprintf(stdout, "name: %s, score: %f\n", name, score); /*写入到标准输出设备*/
return 0;
}