-4

I need a program that can make me multiple accouts stored in different files. This is what I've done so far but for some reason ("test" + userName + ".txt", "a"); does not work. Thank you for your time!

 
int main() {

char choice[10];
printf("create accout (1)");
printf("\nlogin to accout (2)\n");
scanf("%s", &choice);
getchar();

if (strcmp(choice, "1") == 0)
{
    char userName[1000];

    FILE *myFile;
    myFile = fopen("test" + userName + ".txt", "a");
    if (myFile == NULL) 
    {
        printf("file does not exist");
    } 
    else 
    {
        printf("Enter your username: ");
        gets(userName);
        fprintf(myFile, "%s", userName);
        fclose(myFile);
    }
} 

Memoya
  • 1

1 Answers1

0

In C, "strings" (char *), are in fact just pointers to the first element of a zero-terminated array of char, interpreted as a string by the library functions.

You can not simply concatenate such pointers with +, like in some other languages that have explicit string types.

To assemble a string, you'll have to use something like strcat() to an appropriately sized buffer:

 char buffer[MAX_PATH]; 
 ... 
 strcpy(buffer, "test"); 
 strcat(buffer, userName); 
 strcat(buffer, ".txt"); 
 myFile = fopen(buffer, "a");

Alternatively, you can use sprintf():

 int res = sprintf(buffer, "test%s.txt", userName);
 if (res > 0)
 {
     myFile = fopen(buffer, "a");

etc...

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94