int main()
{
FILE *fp;
char ch;
char str[1024],st[11];//str[]用来读取文件中的内容,st[]用来输入内容到文件
fp=fopen("dest.txt","w+");
//fgetc与fputc使用
printf("fputc输入文件,请输入:");
ch=getchar();
while(ch!='\n')
{
fputc(ch,fp);
ch=getchar();
}
rewind(fp);
printf("\nfgetc输出文件,输出为:");
ch=fgetc(fp);
while(ch!=EOF)
{
putchar(ch);
ch=fgetc(fp);
}
fclose(fp);
//fgets与fputs
if((fp=fopen("dest.txt","r+"))==NULL)
{
printf("error\n");
exit(-1);
}
printf("\n\nfgets读取文件中的内容:");
fgets(str,1024,fp);
printf("%s\n",str);
fclose(fp);
if((fp=fopen("dest.txt","a"))==NULL)
{
printf("error\n");
exit(1);
}
printf("\n使用fputs追加内容:");
scanf("%s",st);
fputs(st,fp);//文件写入成功!
fclose(fp);
fp=fopen("dest.txt","r");
printf("\n使用fgets把内容完全读完!:\n");
while(fgets(str,5,fp)!=NULL)
{
printf("%s",str);
}
fclose(fp);
//fread与fwrite
fp=fopen("dest.txt","w");
printf("\n\n使用fwrite写到文件:");
scanf("%s",str);
fwrite(str,sizeof(int),1,fp);
fclose(fp);
fp=fopen("dest.txt","r");
printf("\n使用fread读文件到屏幕:");
fread(st,sizeof(int),1,fp);
printf("%s",st);
fclose(fp);
//fscanf与fprintf
fp=fopen("dest.txt","w");
printf("\n\nfprintf读内容到文件:");
scanf("%s",st);
fprintf(fp,"%s",st);
fclose(fp);
fp=fopen("dest.txt","r");
printf("\nfscanf写文件到str:");
fscanf(fp,"%s",str);
printf("%s\n",str);
fclose(fp);
return 0;
}
C语言文件读写例题,fgetc,fputc,fgets,fputs,fread,fwrite,fscanf,fprintf
最新推荐文章于 2024-07-22 09:00:00 发布