简体   繁体   English

无法使用fopen()打开文件

[英]Can't open a file using fopen()

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. 这里的问题是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();
}

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. 例如,使用strcpy()将名称复制到一个新数组,然后使用strcat()添加“ .txt”,但它也不起作用。 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 希望你能帮我

List of problems: 问题清单:

  1. You have not declared fp (at least in shown code) before trying to use it. 在尝试使用fp之前,您尚未声明它(至少在显示的代码中)。 Change line to: 将行更改为:

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

  2. You have not declared nombre . 您尚未声明nombre Add line: 添加行:

    char nombre[11];//to match size of name char nombre [11]; //以匹配name大小

(Or, you may have meant to use name ?) (或者,您可能打算使用name ?)

  1. Everywhere it exists in your code, comment out the line: 在代码中的任何地方,请注释掉以下行:

    //fflush(stdin); // fflush(stdin);

  2. Change the line 换线

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

to: 至:

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

Just figured it out, I had to change the line 刚弄清楚,我不得不换线

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

And instead use fscanf() just like this: 而是像这样使用fscanf():

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

the question was not clear about the actual format of the data within the file. 有关文件中数据的实际格式的问题尚不清楚。 So I decided to use a format of name password for each line of the file. 因此,我决定为文件的每一行使用name password的格式。

Here is a version of the code that cleanly compiles and performs the desired function. 这是干净地编译并执行所需功能的代码版本。

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM