should i inset a fwrite in the for loop of "i"?
Printable View
should i inset a fwrite in the for loop of "i"?
what is the real problem plz i don't understand
I would guess that one difficulty is that you seem to have a fetish for writing/reading from a file, rather than using the array in memory that you have and passing it around in a parameter or whatever. If the point is that everything is supposed to leave the database on disk in the proper state, then that's great, but you must always write back to disk before calling any other function, especially any function that's going to try to read back the database first thing.
The for-loop of i looks like a reasonable place to put it in this case; close the file handle first, open the file for writing, and off you go. On the other hand, I thought you had a function whose sole job was to write out the database to file when passed the array -- why not use it?
the problem i guess is within the deleting loop. In fact, after the execution of this fuction it delete all except the last one
Code:void account_delete(char *filename)
{
int count=0,i=0,g,h;
char NAME[20];
account t[20];
FILE *file=fopen(filename,"rb");
if(file!=NULL)
{
while(fread(&t[i],sizeof (account),1,file)==1)
{
i++;
count++;
}
}
printf("give the name of account to delete");
scanf("%s",&NAME);
for( g=0;g<count;g++)
{if(strcmp(t[g].name,NAME)==0)
{ for(h=g;h<count;h++)
{
t[h]=t[h+1];
}
}
}
count--;
for(i=0;i<count;i++)
{
account_overwrite(filename,t[i]);//this open the file in "wb" and write to content of t[i] in the file. This one still works with other functions.
}
fclose(file);
view_account(filename);
}
any idea?
I'm assuming that if you put a debug print in your account_overwrite loop that it would say you are printing the correct number of records. (If not, then you need to look at that.) Can you verify file sizes? (In other words, after this happens, is the file the right size for however many records it's suppose to have?) You say that the only record is the last one -- is that what you would see from the file itself, or is that what view_account is telling you? (Maybe there's something wrong with view_account.)
well here's the view account stuff. It works fine the other function but displays only the last account created is displayed
Code:void view_account(char *filename)
{
int count=0;
int i=0;
account t[30];
FILE *file=fopen(filename,"rb");
if(file!=NULL)
{
while(fread(&t[i],sizeof (account),1,file)==1)
{
i++;
count++;
}
}
printf( "Acc.Name | Password| Privilege");
for(i=0;i<count;i++)
{
printf("\n %s | %s | %s\n ",t[i].name,t[i].password,t[i].previleges);
}
}
this problem is only in when this is called in the delete function