我在项目中有这两个功能,可以将用户信息加载并保存到文件中。每个用户都保存在文件的新行中。我的问题是当我尝试使用ftell(f)时程序崩溃了。当我打印ftell(f)时,它用fopen()打开文件后打印-1。我试图在errno中看到错误,但是在fopen()之后打印“NO ERROR”,但是一旦我使用fseek修改文件指针f位置,就会打印“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");
}
答案 0 :(得分: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 ) {
...
你在一条线上做的越多,你犯错的可能性就越大。正确编程很难。不要做那些让事情变得更难的事情 - 比如试着看看你能把多少代码塞进一行。