文件操作问题

时间:2014-07-03 03:15:01

标签: c file-io

我在写一段代码时遇到了很多问题。我也不确定什么是错的。

这是我尝试的代码:

#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;
}

终极告诉我的是这里。

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]

2 个答案:

答案 0 :(得分:0)

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

fopen不是可变函数,它不支持%s等格式说明符。使用sprintfstrcpy创建文件名字符串,然后使用它调用fopen


另一个问题是scanf

scanf("%s", &username);

usernamechar的数组,并转换为指向char的指针,此处您不需要&

scanf("%s", username);

答案 1 :(得分:0)

fopen函数为fopen ("file", "r");你有3个参数用于这个功能。你可以使用

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

我更喜欢使用gets函数来获取字符串:

char username[100];
gets(username);