标准文件读写操作
1、编程实现读出磁盘文件datafile.txt中的内容,将它们显示在屏幕上
3、逐行读出datafile.txt文件中的字符并显示出来
4、从键盘输入若干行字符,把它们添加到磁盘文件datafile.txt中
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
if((fp=fopen("c:\\datafile.txt","r"))==NULL)
{
printf("file cannot be opened!\n");
exit(1);
}
while((ch=fgetc(fp))!=EOF)
fputc(ch,stdout);
fclose(fp);
getch();
}
2、编程完成从键盘输入字符后,写入到磁盘文件datafile.txt中#include<stdlib.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
if((fp=fopen("c:\\datafile.txt","r"))==NULL)
{
printf("file cannot be opened!\n");
exit(1);
}
while((ch=fgetc(fp))!=EOF)
fputc(ch,stdout);
fclose(fp);
getch();
}
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
if((fp=fopen("c:\\datafile.txt","w"))==NULL)
{
printf("file cannot be opened!\n");
exit(1);
}
while((ch=fgetc(stdin))!='\n')
fputc(ch,fp);
fclose(fp);
getch();
}
#include<stdlib.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
if((fp=fopen("c:\\datafile.txt","w"))==NULL)
{
printf("file cannot be opened!\n");
exit(1);
}
while((ch=fgetc(stdin))!='\n')
fputc(ch,fp);
fclose(fp);
getch();
}
3、逐行读出datafile.txt文件中的字符并显示出来
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
FILE *fp;
char buffer[64];
if((fp=fopen("c:\\datafile.txt","r"))==NULL)
{
printf("file cannot be opened!\n");
exit(1);
}
while(!feof(fp))
{
if(fgets(buffer,64,fp)!=NULL)
printf("%s",buffer);
}
fclose(fp);
getch();
}
#include<stdlib.h>
#include<conio.h>
void main()
{
FILE *fp;
char buffer[64];
if((fp=fopen("c:\\datafile.txt","r"))==NULL)
{
printf("file cannot be opened!\n");
exit(1);
}
while(!feof(fp))
{
if(fgets(buffer,64,fp)!=NULL)
printf("%s",buffer);
}
fclose(fp);
getch();
}
4、从键盘输入若干行字符,把它们添加到磁盘文件datafile.txt中
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
void main()
{
FILE *fp;
char buffer[64];
if((fp=fopen("c:\\datafile.txt","a"))==NULL)
{
printf("file cannot be opened!\n");
exit(1);
}
while(strlen(fgets(buffer,64,stdin))>1)
{
fputs(buffer,fp);
fputs("\n",fp);
}
fclose(fp);
getch();
}
#include<stdlib.h>
#include<conio.h>
#include<string.h>
void main()
{
FILE *fp;
char buffer[64];
if((fp=fopen("c:\\datafile.txt","a"))==NULL)
{
printf("file cannot be opened!\n");
exit(1);
}
while(strlen(fgets(buffer,64,stdin))>1)
{
fputs(buffer,fp);
fputs("\n",fp);
}
fclose(fp);
getch();
}