I suppose perfect is when the code works according to specification without any bugs or memory leaks. That usually take a few rounds.
One thing to think of is to try to make the code as readable as possible. That includes both the formatting of the code and the number of lines you have in a function.
For me it is more difficult to read code written like this
if ( ( fp=fopen("user.dat", "a+")) == NULL) {
if ( ( fp=fopen("user.dat", "w+")) == NULL) {
printf ("Could not open file\n");
exit ( 1);
}
}
compared to this
if ((fp = fopen("user.dat", "a+")) == NULL)
{
if ((fp=fopen("user.dat", "w+")) == NULL)
{
printf("Could not open file\n");
exit(1);
}
}
This is of course a matter of taste, and the important thing is to be consistent and follow any guidelines in your organisation.
That said there a couple of things in your code that can be improved.
1. Always initialize variables to a default value.
Such as
FILE *fp = NULL;
1.a. Use calloc instead of malloc
pUser=(struct user *)malloc(sizeof(struct user));
pUser = (struct user*)calloc(1, sizeof(struct user));
calloc initializes the allocated memory to 0.
2. fopen("user.dat", "a+")
This statement actually creates the file if it doesn't exist, so the next if-statement is not necessary.
3. If you the fopen function fails you should check the
errno
variable for more information about what went wrong.
4. You can also see that you are using the same code block in both cases
So better make a function of like
FILE* OpenFile(const char* fileName)
{
if ((fp = fopen(fileName, "a+")) == NULL)
{
printf("Could not open file: '%s'\n", fileName);
exit(1);
}
)
5. switch statements tend to be difficult to read when you add more cases, so it is better to create functions for each case.
switch(i)
{
case 1: fp = OpenFile("user.dat");
OpenAccount();
break;
case 2: fp = OpenFile("user.dat");
CreateAccount();
break;
default: printf("This case is not available\n");
exit(1);
}
6. The password
Never store passwords as readable text.
Use a hash algorithm, like SHA1, and store the hashed value instead.
Then when the user login you calculate the password he/she enters and compare with the value you have stored.
See for example
http://stackoverflow.com/questions/5189257/sha1-function-in-cpp-c[
^]
That was all I had the energy to point out for now.