C语言文件读写实例
//编程完成读出文件sfile.txt中的内容,反序写入另一个文件dfile.txt中去。#include#define BUFFSIZE 5000void main(){FILE * sfp,* dfp;int i;char buf[BUFFSIZE];if((sfp=fopen("C:\\sfile.txt","r"))==NULL) /*
//编程完成读出文件sfile.txt中的内容,反序写入另一个文件dfile.txt中去。
#include<stdio.h>
#define BUFFSIZE 5000
void main()
{
FILE * sfp,* dfp;
int i;
char buf[BUFFSIZE];
if((sfp=fopen("C:\\sfile.txt","r"))==NULL) /*以只读方式打开*/
{
printf("Source file cannot be opened\n");
exit(1);
}
if(!(dfp=fopen("C:\\dfile.txt","w"))) /*以只写方式打开*/
{
printf("Destination file cannot be opened\n");
exit(1);
}
i=0;
while(!feof(sfp)) /*判断是否文件尾,不是则循环*/
{
buf[i++]=fgetc(sfp); /*读出数据送缓冲区*/
if(i>=5000) /*若i超出5000,程序设置的缓冲区不足*/
{
printf("buffer not enough!");
exit(1);
}
}
while(--i>=0) /*控制反序操作*/
fputc(buf[i],dfp); /*写入目的文件中*/
fclose(sfp);
fclose(dfp);
}
//从键盘输入字符后,写入到磁盘文件datafile1.txt中
#include<stdio.h>
void main()
{
FILE * fp1;
char str1;
if((fp1=fopen("C:\\datafile1.txt","w"))==NULL)
{
printf("file cannot be opened\n");
exit(1);
}
while((str1=fgetc(stdin))!='\n')
fputc(str1,fp1);
fclose(fp1);
}
//读出磁盘文件datafile.txt中的内容,将它们显示在屏幕上
#include<stdio.h>
void main()
{
FILE * fp;
char str1;
if((fp=fopen("C:\\datafile.txt","r"))==NULL)
{
printf("file cannot be opened\n");
exit(1);
}
while((str1=fgetc(fp))!=EOF)
fputc(str1,stdout);
fclose(fp);
}
更多推荐



所有评论(0)