-1

我在一个项目中有这两个函数,它将用户信息加载并保存到一个文件中。每个用户都保存在文件的新行中。我的问题是当我尝试使用 ftell(f) 时程序崩溃了。当我打印 ftell(f) 时,它会在使用 fopen() 打开文件后打印 -1。我试图在 errno 中查看错误,但是一旦我使用 fseek 修改文件指针 f 位置,它会在 fopen() 之后打印“NO ERROR”但是“INVALID ARGUMENT”。

我的问题出在我的 Load_File 函数中,但我也显示了 Save_File 函数以检查我在文件中是否正确写入。

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

LIST Load_File(LIST L){
    //PRE: receive a void list (L==NULL)
    //POST: returns an user's loaded from file
    USER user; //node of list

    char str[150]; 

    //User's structure
    char name[30];
    char CI[10];
    char email[30];
    char city[30];
    char password[30];

    errno=0;

    FILE *f;
    if(f=fopen("DATOS.txt","r")==NULL){
        printf("File not found. \n");
        return L;
    }


    //Code for verify what's happening
    printf("FTELL: %d/n", ftell(f)); //prints -1
    printf("ERRNO: %s\n", strerror(errno)); //prints NO ERROR
    fseek(f, 0, SEEK_CUR);
    printf("FTELL: %d\n", ftell(f)); //still prints -1
    printf("ERRNO: %s\n", strerror(errno)); //prints INVALID ARGUMENT
    printf("FEOF: %d\n",feof(f)); //CRASHES! (a)

    while(feof(f)==0){ //CRASHES when (a) line is deleted

        //Load line of file in user's structure
        fgets(str, 150, f);
        sscanf(str,"%s %s %s %s %s ",name, CI, email, city, password);
        //Copy into structure's parts
        strcpy(user->name, name);
        strcpy(user->CI, CI);
        strcpy(user->email, email);
        strcpy(user->city, city);
        strcpy(user->password, password);

        Add_user_to_list(L, user);
    }

    if(fclose(f)!=0) printf("\n\n FILE NOT PROPERLY ClOSED \n\n");
}

void Save_File(LIST L){
    //PRE: receive an user's list
    //POST: saves a new list in file

    FILE *f;
    int flag=0;

    f=fopen("DATOS.txt","w");
    if(f==NULL){
        printf("Error opening file f\n");
    }
    if(!L_Void(L)){
        L=L_First(L);
        do{
            if(flag) L=L_Next(L);
            flag=1;
            fprintf(f,"%s %s %s %s %s \n",L_InfoM(L)->name,L_InfoM(L)->CI, L_InfoM(L)->email, L_InfoM(L)->city, L_InfoM(L)->password);
        }while(!L_Final(L));
    }else printf("List is void, then nothing was saved.\n");

    if(fclose(f)!=0) printf("\n\n FILE NOT PROPERLY COSED \n\n");
}
4

1 回答 1

2

这段代码是错误的:

if(f=fopen("DATOS.txt","r")==NULL){

二元运算符(例如)的==优先级高于赋值运算符(例如=.

所以你的代码被解析为:

if(f=( fopen("DATOS.txt","r")==NULL ) ){

逻辑==比较的结果分配给f

你为什么要把作业塞进if语句?这更清晰,并且更容易出错:

FILE *f = fopen( "DATOS.txt", "r" );
if ( NULL == f ) {
...

你在一条线上做的越多,你犯错误的可能性就越大。正确编程已经够难了。不要做让它变得更难的事情——比如试着看看你可以在一行中塞进多少代码。

于 2016-12-05T01:58:19.250 回答