我在一个项目中具有这两个功能,该功能将用户的信息加载到文件中。每个用户都保存在文件的新行中。我的问题是,当我尝试使用ftell(f)时,程序崩溃。当我打印ftell(f)时,它在用fopen()打开文件后打印-1。我尝试在Errno中查看错误,但是在Fopen()()之后它打印了"无错误",但是一旦我使用FSEEK修改文件指针F位置。
。我的问题在我的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: %sn", strerror(errno)); //prints NO ERROR
fseek(f, 0, SEEK_CUR);
printf("FTELL: %dn", ftell(f)); //still prints -1
printf("ERRNO: %sn", strerror(errno)); //prints INVALID ARGUMENT
printf("FEOF: %dn",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("nn FILE NOT PROPERLY ClOSED nn");
}
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 fn");
}
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("nn FILE NOT PROPERLY COSED nn");
}
此代码是错误的:
if(f=fopen("DATOS.txt","r")==NULL){
二进制运算符 - 例如==
-比分配操作员具有更高的优先级 - 这样的=
。
因此,您的代码被解析为:
if(f=( fopen("DATOS.txt","r")==NULL ) ){
逻辑==
比较的结果分配给f
。
为什么要将作业塞入if
语句中?这要清楚得多,并且是 lot 较小的错误:
FILE *f = fopen( "DATOS.txt", "r" );
if ( NULL == f ) {
...
您在一行上做的越多,您就越有可能犯错。正确编程就足够了。不要做使它变得更难的事情 - 就像尝试查看可以将多少代码塞入一行中。