I'm just starting to learn files. For this eI'm trying to create a program that keeps track of transaction records in a store. The first step is to record a day's transactions. I create a file trans.c that I can have open alongside my main.c file, so as to keep track of it. I then fill in trans.c first with empty structs to allocate memory for the transaction records, then I fill it in with structs containing client data using fwrite.
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
struct clientData {
int num;
char fName [20];
char lName[20];
long double balance;
};
void createFiles (FILE *fNew, FILE *fOld, FILE *fTrans, struct clientData x);
void fillTrans (FILE *fTrans, struct clientData x);
int main() {
FILE *fTrans; //transaction file
FILE *fNew; //new master file
FILE *fOld; //old master file
struct clientData blankClient = {0, "", "", 0.0 };
if ((fTrans = fopen("trans.c", "wb")) == NULL) {
printf("Error. File could not be opened.\n");
}
else {
int i;
for (i = 1; i <= 100; i++) {
fwrite(&blankClient, sizeof(struct clientData), 1, fTrans);
}
}
fillTrans(fTrans, blankClient);
}
void fillTrans(FILE *fTrans, struct clientData x) {
if ((fTrans = fopen("trans.c", "a+")) == NULL) {
printf("File could not be opened.");
}
else {
printf("Enter the account info, or 0 to quit.\n");
scanf("%d%s%s%Lf", &x.num, x.fName, x.lName, &x.balance);
while (x.num!= 0) {
fseek(fTrans, (x.num - 1) * sizeof(struct clientData), SEEK_SET);
fwrite(&x, sizeof(struct clientData), 1, fTrans);
fscanf(stdin, "%d%s%s%Lf", &x.num, x.fName, x.lName, &x.balance);
}
fclose(fTrans);
}
}
When I go back to trans.c to see if it had worked, the file remains empty, and yet my code compiles without issue, and in run time I don't seem to have trouble filling in the structs and writing them in. Is the file being filled in elsewhere, or am I missing something/doing this wrong?
fillTrans()are probably being lost because you haven't closed the file before you call it.main()hasn't ended yet when you callfillTrans().