C语言练习


[例11.1] 将键盘输入的一行字符存入d盘的myfile1.txt文件中。
#include <stdio.h>
main()
{ FILE *out_fp;
char ch;
if((out_fp=fopen("d:\\myfile1.txt","w"))==NULL)
{ printf("不能建立d:\\myfile1.txt文件。\n");
exit(1);
}
while((ch=getchar())!='\n')
fputc(ch,out_fp);
close(out_fp);
}

[例11.2] 将例11.1建立的d:\myfile1.txt文本文件中的字符,全部显示在屏幕上,并统计总共有多少个字符。
#include <stdio.h>
main()
{ FILE *in_fp;
char ch;
int n=0;
if((in_fp=fopen("d:\\myfile1.txt","r"))==NULL)
{ printf("不能读取d:\\myfile1.txt文件。\n");
exit(1);
}
while((ch=fgetc(in_fp))!=EOF) /* 文本文件没结束时 */
{ putchar(ch);
n++;
}
close(in_fp);
printf("\n共读入了 %d 个字符。\n",n);
}

例11.3 文件复制
#include <stdio.h>
main()
{ FILE *from_fp,*to_fp;
char from_filename[80],to_filename[80],ch;
printf("源文件名:");scanf("%s",from_filename);
printf("目标文件名:");scanf("%s",to_filename);
if((from_fp=fopen(from_filename,"rb")==NULL) /* 只读打开二进制文件 */
{ printf("%s源文件无法使用。\n",from_filename);
exit(1);
}
if((to_fp=fopen(to_filename,"wb"))==NULL) /* 只写打开二进制文件 */
{ printf("%s目标文件无法创建。\n",to_filename);
exit(1);
}
while(!feof(from_filename)) /* 源二进制文件没结束时 */
{ ch=fgetc(from_filename);
fputc(ch,to_filename);
}
fclose(from_filename);
fclose(to_filename);
}

例11.4 将一批字符串写入文件
#include <stdio.h>
main()
{ FILE *f;
char *str[]={"red","blue","yellow","green","black"};
int i;
f=fopen("d:\\myfile4.txt","w");
for(i=0;i<5;i++)
fputs(str[i],f);
fclose(f);
}

例11.5 将MyDoc.txt文本文件的内容显示在屏幕上。该文本文件由许多行组成,并且每一行的最大长度不超过1024个字符。
#include <stdio.h>
#define MaxChars 1024
main()
{ FILE *f;
char str[MaxChars];
f=fopen("d:\\MyDoc.txt","r");
while(fgets(str,MaxChars,f))
printf("%s",str);
fclose(f);
}

