I've corrected some bugs in my code and it quite works..
Once I call the function, the file is opened in read mode.. if nothign can be read, I close it, open it again in append mode and write the string. If something is readable, I check if some of the previous entry was the same of the one I have here, if not, I write it, otherwise I trash the string.
The problem is that It seems to fail at the second cycle because it doesn't check the first written string.. check out the code:
Code:
int writeDatabase(char* mail) {
char startToken[MAX_PATH]= "\0";
char tokentemp[MAX_PATH]= "\0";
database = fopen("database.txt", "rt");
printf("Want to write %s\n", mail);
// if the file is empty
if ((fgets(startToken, MAX_PATH, database)) == NULL) {
//printf("empty\n");
fclose(database); // closing read only
// then I will write the first string in the file
database = fopen("database.txt", "at"); // opening append
fputs(mail,database);
fputs("\n",database);
fclose(database); // closing append
printf("Written at the beginning -> %s\n", mail);
} else { // if the file contains some strings
while(fgets(tokentemp, MAX_PATH, database)!= NULL) {
//printf("Iterating on string %s \n", tokentemp);
// analyzing the single token, looking for a previous
// entry of the mail
if (strstr(tokentemp, mail) != NULL) {
// previously written
printf("Found\n");
fclose(database); // closing read only
return 0;
}
}
// otherwise the mail is new, then write it
fclose(database); // closing read only
database = fopen("database.txt", "at"); // opening append
fputs(mail,database);
fputs("\n",database);
printf("Written -> %s\n", mail);
fclose(database); // closing append
}
return 0;
}
Code:
FILE* database;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char* lpCmdLine, int nCmdShow) {
// creating the file
database = fopen("database.txt", "w");
fclose(database);
writeDatabase("marco");
writeDatabase("marco");
writeDatabase("ciao");
writeDatabase("ciao");
writeDatabase("marco");
writeDatabase("marco");
writeDatabase("ciao");
writeDatabase("miao");
writeDatabase("miao");
system("PAUSE");
return 0;
}
the debug (printf) output is :
Want to write marco
Written at the beginning -> marco
Want to write marco
Written -> marco
Want to write ciao
Written -> ciao
Want to write ciao
Found
Want to write marco
Found
Want to write marco
Found
Want to write ciao
Found
Want to write miao
Written -> miao
Want to write miao
Found
As you can seen, the second time I add "marco" it's added without succeding while checking if it was previously entered (it was entered the first time, just before!)
and the file contains:
as you can see there is a duplicated marco..
any hints? thanx!