I'm writing a program that simulates a platform where users can register. In register function I ask the user for his username and the program should create a new file with username as file name to store his password and other data for other functions. Problem here is that fopen returns NULL which means that it can't be created.
void Register()
{
char name[11];
char password[11];
char aux[11];
system("cls");
FILE *fp=fopen("Users.txt","a+"); //I've created this .txt, just has one user which is admin
if (fp==NULL){
printf("\nFile cant be opened");
getchar();
return;
}
printf("Write a new username (no more than 10 characters, no spaces) ");
fflush(stdin);
fgets(name,sizeof(name),stdin);
getchar();
do{
if((fgets(aux,sizeof(aux),fp))!=NULL){ //Checks is reading lines
if ((strcmp(name,aux))==0){ //Username already exists
printf("\nUsername already exists, try another: ");
fflush(stdin);
fgets(name,sizeof(name),stdin);
rewind(fp); //Takes pointer to the beginning
}
}
}while(!(feof(fp)));
fseek(fp,0,SEEK_END); //Takes pointer to end
fprintf(fp,"%s",name);
fclose(fp);
fp=fopen(name,"w"); /*THIS IS WHERE IT FAILS, RETURNS NULL*/
if (fp==NULL){
printf("\nFile cant be opened");
getchar();
return;
}
printf("\nChoose a password(no more than 10 characters): ");
fflush(stdin);
fgets(password,sizeof(password),stdin);
getchar();
fprintf(fp,"%s\n",name);
fprintf(fp,"%s",password);
fclose(fp);
printf("\nUser successfully registered\nName: %s\nPassword: %s",name,password);
getchar();
}
I've already tried with another method. For example, use strcpy() to copy name to a new array and then strcat() to add ".txt" but it doesn't work either. Like this:
[...]
char aux2[20];
strcpy(aux2,name);
strcat(aux2,".txt");
fp=fopen(aux2,"w"); /*FAILS TOO */
if (fp==NULL){
printf("\nFile cant be opened");
getchar();
return;
}
Can't figure out what is going wrong. Hope you can help me