0

I'm getting a lot of problems with a piece of code I'm writing. I'm not exactly sure whats wrong either.

Here's the code I'm trying:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[]) {

    char pass[10];
    FILE *fp;
    char username[10];

    system("clear");    
    printf("\nWelcome to Sign-Up Testing.");
    printf("\nWhat UserName would you like?");
    printf(" Max 10 characters.");
    printf("\n\n>>>");
    scanf("%s", &username);
    fp = fopen("%s.dgf", username,"r");
    if(fp != NULL) {
        printf("\n%s is already taken.\n");
        sleep(1);
        return 0;
    }
    else if(fp == NULL){
        fopen("%s.dgf", username,"w");
        printf("\nPassword:\n");
        scanf("%s", &pass);
        fprintf(fp,"%s", pass);
        printf("\nThank you for signing up!");
    }


    return 0;
}

Here's what Terminal told me.

Sign-Up.c: In function ‘main’:
Sign-Up.c:15:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[10]’ [-Wformat]
Sign-Up.c:16:2: error: too many arguments to function ‘fopen’
/usr/include/stdio.h:273:14: note: declared here
Sign-Up.c:18:3: warning: format ‘%s’ expects a matching ‘char *’ argument [-Wformat]
Sign-Up.c:23:3: error: too many arguments to function ‘fopen’
/usr/include/stdio.h:273:14: note: declared here
Sign-Up.c:25:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[10]’ [-Wformat]
tshepang
  • 12,111
  • 21
  • 91
  • 136
DarkSun
  • 41
  • 2
  • 6
  • If you intend to treat `username` as a `'\0'`-terminated string, then the maximum numbers of characters should be 9 instead of 10. – binki Jul 03 '14 at 03:48

2 Answers2

0
fp = fopen("%s.dgf", username,"r");

fopen isn't a variadic function, it doesn't support format specifiers like %s. Use sprintf or strcpy to make the filename string, and then call fopen with it.


Another problem is with scanf:

scanf("%s", &username);

username is an array of char, and is converted to a pointer to char, you don't need & here:

scanf("%s", username);
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

The fopen function is fopen ("file", "r"); you have 3 parameters for this function. You can use

fopen(strcat("%s.dgf",username),"r");

And I prefer to use the gets function to obtain a string:

char username[100];
gets(username);
Jongware
  • 22,200
  • 8
  • 54
  • 100
  • 1
    Is it too late for you to change your preference for `gets` to something [safer](http://stackoverflow.com/questions/20753495/prevent-buffer-overflows-with-gets)? – Jongware Jul 03 '14 at 08:46