无法使用fopen()打开文件

时间:2017-03-19 17:19:55

标签: c file fopen

我正在编写一个模拟用户可以注册的平台的程序。在注册功能中,我向用户询问他的用户名,程序应该创建一个新的文件,用户名作为文件名,以存储他的密码和其他功能的其他数据。这里的问题是fopen返回NULL,这意味着它无法创建。

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();
}

我已经尝试过另一种方法了。例如,使用strcpy()将名称复制到新数组,然后使用strcat()添加“.txt”,但它也不起作用。像这样:

[...]
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;
}

无法弄清楚出了什么问题。希望你能帮帮我

3 个答案:

答案 0 :(得分:1)

问题清单:

  1. 在尝试使用之前,您尚未声明fp(至少在显示的代码中)。 将行更改为:

    FILE * fp = fopen(“Users.txt”,“a +”);

  2. 您尚未声明nombre。添加行:

    char nombre [11]; //匹配name

  3. 的大小

    (或者,您可能打算使用name?)

    1. 它存在于您的代码中,注释掉该行:

      // fflush(标准输入);

    2. 更改行

       fp=fopen(name,"w"); /*THIS IS WHERE IT FAILS, RETURNS NULL*/ 
      
    3. 到:

      fp=fopen(name,"w+"); /*THIS IS WHERE IT FAILS, RETURNS NULL*/
      

答案 1 :(得分:0)

刚想通了,我不得不换行

if((fgets(aux,sizeof(aux),fp))!=NULL){ //Checks is reading lines

而是像这样使用fscanf():

if((fscanf(fp,"%s",&aux)==1){ //Checks if is reading a string (a line)

答案 2 :(得分:0)

问题尚不清楚文件中数据的实际格式。所以我决定为文件的每一行使用name password格式。

这是一个干净地编译并执行所需功能的代码版本。

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

void Register( void );

void Register( void )
{
    char name[11];
    char password[11];
    char aux[11];

    system("cls");

    printf("Write a new username (no more than 10 characters, no spaces) ");
    if( !fgets(name,sizeof(name),stdin) )
    {
        fprintf( stderr, "fgets for user name failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fgets successful

    // code should remove trailing new line, if any
    char *newline;
    if( (newline = strchr( name, '\n' ) ) )
    {
        *newline = '\0';
    }

    FILE *fp=fopen("Users.txt","a+"); //I've created this .txt, just has one user which is admin
    if ( !fp)
    {
        perror("fopen for Users.txt for read/write failed");
        getchar();
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    while( fgets(aux,sizeof(aux),fp) )
    { //Checks is reading lines
        // separate out the name field
        char *token = strtok( aux, " " );
        if( token )
        {
            if ((strcmp(name,aux))==0)
            { //Username already exists
                printf("\nUsername already exists, try another: ");
                rewind(fp); //Takes pointer to the beginning
            }
        }
    }

    // name not already in file

    printf("\nChoose a password(no more than 10 characters): ");

    if( !fgets(password,sizeof(password),stdin) )
    {
        perror( "fgets for password failed" );
        fclose( fp ); // cleanup
        exit( EXIT_FAILURE );
    }

    // implied else, fgets successful

    //remove trailing newline
    if( (newline = strchr( password, '\n' ) ) )
    {
        *newline = '\0';
    }

    fprintf(fp,"%s %s\n",name, password);

    fclose(fp);

    printf("\nUser successfully registered\nName: %s\nPassword: %s",name,password);
    getchar();
}  // end function: Register