fputc fgetc 可以用来读写文件中的一个字符
1.一批数据是以文件的形式 存放在外部介质中,
2.操作系统是以文件为单位对数据进行管理的!
3.把一个字符写到磁盘上去!
fputc(ch,fp);
函数的作用是将字符(ch的值)输出到fp所指的文件中去!
#define putchar(c) fputc(c,stdout)
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char ch,filename[10];
printf("Please input you create file name/n");
scanf("%s",filename);
getchar();
if((fp=fopen(filename,"w"))==NULL)
{
printf("can not open file/n");
exit(0);
}
printf("Please input Content/n");
ch=getchar();
while(ch!='#')
{
fputc(ch,fp);
ch=getchar();
}
putchar(10);
fclose(fp);
return 0;
}
4.从指定的文件读入一个字符 该文件必须是以读或以读写的方式打开,
ch=fgetc(fp);
while(ch!=EOF)
{
ch=fgetc(fp);
}
函数feof(fp)
判断文件是否真的结束:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *in,*out;
char ch,infile[10],outfile[10];
printf("Enter the infile name:/n");
scanf("%s",infile);
printf("Enter the outfile name/n");
scanf("%s",outfile);
if((in=fopen(infile,"r"))==NULL)
{
printf("can not open file/n");
exit(0);
}
if((out=fopen(outfile,"r"))==NULL)
{
printf("can not open file/n");
exit(0);
}
while(!feof(in))
{
fputc(fgetc(in),out);
}
fclose(in);
fclose(out);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
FILE *in,*out;
if(argc!=3)
{
printf("You forgot to enter a filename/n");
exit(0);
}
if((in=fopen(argv[1],"r"))==NULL)
{
printf("cannot open infile/n");
exit(0);
}
if((out=fopen(argv[2],"w"))==NULL)
{
printf("cannot open outfile/n");
exit(0);
}
while(!feof(in))
{
fputc(fgetc(in),out);
}
fclose(in);
fclose(out);
return 0;
}
执行过程 就不用说啦! 自己想吧!
#include<stdio.h>
#include<stdlib.h>
#define SIZE 2
struct student_type
{
char name[10];
int num;
int age;
char addr[15];
}stud[SIZE];
void save()
{
FILE *fp;
int i;
if((fp=fopen("stu_list.c","wb"))==NULL)
{
printf("cannot open file/n");
return ;
}
for(i=0;i<SIZE;i++)
if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf("file write error/n");
fclose(fp);
}
void load()
{
int i;
FILE *fp;
if((fp=fopen("stu_list.c","rb"))==NULL)
{
printf("cannot open infile/n");
}
for(i=0;i<SIZE;i++)
{
if((fread(&stud[i],sizeof(struct student_type),1,fp))!=1)
{
if(feof(fp))
{
fclose(fp);
return;
}
printf("file read error/n");
}
}
fclose(fp);
}
int main()
{
int i;
printf("Please input student Name Num Age Addr/n");
for(i=0;i<SIZE;i++)
{
scanf("%s%d%d%s",stud[i].name,&stud[i].num,&stud[i].age,stud[i].addr);
}
save();
load();
return 0;
}