The code does not work tho, it still initializes the file everytime i run the program
You cannot retain program state in the program across multiple runs. Every run of the program starts with a clean slate. Depending on the system on which it runs, however, you can generally retain state in the system. In this case, the natural state is whether the adminAcc.txt
file exists, and possibly whether it has valid contents.
Although it is possible to check that before trying to open the file, a better paradigm is usually simply to attempt an operation (such as opening the file) and seeing whether that works. Because you need to do that anyway, and it's always possible for the system to be modified at just the right time such that the wanted operation fails even though an appropriate pre-check predicts that it will succeed.
So, something along these lines would make sense, then:
#include <stdio.h>
#include <string.h>
void initAdminIfNecessary(){
struct form adminAcc;
FILE *fptr;
if((fptr = fopen("adminAcc.txt", "ab")) == NULL){
fprintf(stderr, "\nError Opening Admin File!\n");
abort();
}
long fileSize = ftell(fptr);
if (fileSize == -1) {
fprintf(stderr, "\nError determining Admin File length!\n");
abort();
else if (fileSize == 0) {
strcpy(adminAcc.username, "admin@gmail.com");
strcpy(adminAcc.password, "admin");
strcpy(adminAcc.roles, "admin");
fwrite(&adminAcc, sizeof(struct form), 1, fptr);
// TODO: check return value
} else if (fileSize < sizeof(struct form)) {
fprintf(stderr, "\nAdmin File has invalid content\n");
abort();
}
fclose(fptr);
}
int main(){
initAdminIfNecessary();
return 0;
}
That opens the file as a binary (b) file in append (a) mode, which creates it if it does not already exist, but does not modify it if it does exist. The file is initially positioned at its end (and each write will go to the then-end of the file).
It uses ftell()
to determine the length of the file, and acts accordingly.