#include<conio.h>
#include<stdio.h>
struct stud
{
int rollno;
char name[10];
char add[10];
};
void main()
{
struct stud st;
FILE *fp,*fpp;
char another='y',ch;
int a,choice,i;
printf("***Press 1 to Add record/Create database***\n");
scanf("%d",&a);
if(a==1) /*recording data begins here*/
{
fflush(stdin);
printf("ADD or CREATE NEW?(a/c): "); /*prompt message to add new record to existing database or to create new database*/
scanf("%c",&ch);
if(ch=='a') /*appending file*/
{
add:
ch='a';
fp=fopen("Studm.dat","ab");
while(another=='y' || another=='Y')
{
fflush(stdin);
printf("Enter RollNo. Name & Address\n");
scanf("%d%s%s",&st.rollno,st.name,&st.add);
fwrite(&st,sizeof(st),1,fp);
fflush(stdin);
printf("\nAdd another record?(y/n): "); /*prompt message to add another record*/
scanf("%c",&another);
}
}
if(ch=='c') /*to create new data file*/
{
fp=fopen("Studm.dat","wb");
printf("Enter RollNo. Name & Address\n");
scanf("%d%s%s",&st.rollno,st.name,&st.add);
fwrite(&st,sizeof(st),1,fp);
fflush(stdin);
printf("\nAdd another record?(y/n): ");
scanf("%c",&another);
fclose(fp);
if(another=='y' || another=='Y')
{
goto add; /*go to the append file block above*/
}
}
fclose(fp);
}
每当我在文本编辑器中打开源文件时,给出的所有名称(字符数据)都是可见的,这意味着存储和记录块工作正常。
fflush(stdin);
printf("\n\nCopying data from studm.dat to stud1.data\n\n");
fp=fopen("Studm.dat","rb");
fpp=fopen("Stud1.dat","wb");
while(fread(&st,sizeof(st),1,fp)==1) /*loop block to copy data*/
{
fflush(stdin); /*tried every place for flushing the buffer, before and after fwrite with in the loop*/
fwrite(&st,sizeof(st),1,fpp);
}
fclose(fp);
fclose(fpp);
就像源文件一样,我在执行整个程序代码记录后在文本编辑器中打开了目标文件,直到最后第二条记录都在那里。
printf("\n\nCopying done now reading data from file Stud1.dat\n\n");
fpp=fopen("Stud1.dat","rb");
while(fread(&st,sizeof(st),1,fp)==1)
{
printf("%d %s %s\n",st.rollno,st.name,st.add);
}
fclose(fpp);
getch();
}
我认为问题在于复制块,但我不知道它是否与缓冲区有关,或者我编码错误或错误。