-
c++ help (random access files)
somebody asked me wats wrong with this, but i'm a little rusty with c++ now. does anybody know wats wrong?
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define SIZE 2
typedef struct Account{
int accNum;
char name[10];
}Account;
void newRecord(FILE *);
int main(){
//int i=0;
FILE *cfPtr;
//Account Acc={0,""};
//cfPtr = fopen("Account1.txt", "a+");
if((cfPtr = fopen("Account1.txt", "a+"))==NULL)
printf("File could not be opened!");
newRecord(cfPtr);
/*else{
printf("Enter account number: ");
scanf("%d", &Acc.accNum);
while(Acc.accNum != 0){
printf("Enter account name: ");
fscanf(stdin,"%s", Acc.name);
fseek(fPtr,(Acc.accNum -1)*sizeof(Account), SEEK_SET);
fwrite(&Acc, sizeof(Account),1,fPtr);
printf("Enter account number: ");
scanf("%d", &Acc.accNum);
}//end while
}//end else
*/
fclose(cfPtr);
getch();
return 0;
}//end main
void newRecord(FILE *cfPtr){
Account Acc;
int accNum;
printf("Enter account number: ");
scanf("%d", &Acc.accNum);
fseek(cfPtr,(Acc.accNum-1)*sizeof(struct Account),SEEK_SET);
fread(&Acc, sizeof(Account),1,cfPtr);
printf("Enter account name: ");
scanf("%s", Acc.name);
//Acc.accNum = accNum;
fseek(cfPtr,(Acc.accNum-1)*sizeof(Account),SEEK_SET);
fwrite(&Acc, sizeof(Account),1,cfPtr);
}
Praise Ye JAH
-
well... the main problem i see here is your access mode 'a+' stated for your fopen function ... 'a+' stands for append and read... and is therefore NOT suitable, or not supposed to be suitable for random access... try using 'w+'. But if that does not work can you expand on what type of errors are u getting ....
and another thing.... i dont really like the idea of stating Account as the typedef of struct Account .... i would think that you are supposed to get errors if that was done, but if not I would still change it .... it does not follow logically .... but anyway try out the change of mode for the fopen
-
the person said this was actually the wrong file. but thanx anyways. through my idleness i'm going to catch up back with c by trying to make this program better.
Praise Ye JAH
-
Kev this program is very confusing. I am not sure what he is trying to do but it is not very clear. The use of 'a+' is justified as he only opened it once for reading or writing. I have a problem with his logic though. I ran this program with minor adjustments and it worked fine.
Hope that you really catch up on your C. This should'nt be too much of a challenge though.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules