C語言練習(xí)


[例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文本文件中的字符,全部顯示在屏幕上,并統(tǒng)計(jì)總共有多少個(gè)字符。
#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) /* 文本文件沒結(jié)束時(shí) */
{ putchar(ch);
n++;
}
close(in_fp);
printf("\n共讀入了 %d 個(gè)字符。\n",n);
}

例11.3 文件復(fù)制
#include <stdio.h>
main()
{ FILE *from_fp,*to_fp;
char from_filename[80],to_filename[80],ch;
printf("源文件名:");scanf("%s",from_filename);
printf("目標(biāo)文件名:");scanf("%s",to_filename);
if((from_fp=fopen(from_filename,"rb")==NULL) /* 只讀打開二進(jìn)制文件 */
{ printf("%s源文件無法使用。\n",from_filename);
exit(1);
}
if((to_fp=fopen(to_filename,"wb"))==NULL) /* 只寫打開二進(jìn)制文件 */
{ printf("%s目標(biāo)文件無法創(chuàng)建。\n",to_filename);
exit(1);
}
while(!feof(from_filename)) /* 源二進(jìn)制文件沒結(jié)束時(shí) */
{ 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文本文件的內(nèi)容顯示在屏幕上。該文本文件由許多行組成,并且每一行的最大長(zhǎng)度不超過1024個(gè)字符。
#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);
}

