提问人:Armando Andres Flores 提问时间:12/5/2016 更新时间:12/5/2016 访问量:626
为什么 ftell 打印 -1 作为文件指针的值?为什么 errno 打印出“INVALID ARGUMENT”?
Why ftell prints -1 as value of file pointer? And why errno prints out "INVALID ARGUMENT"?
问:
我在项目中有这两个函数,它将用户信息加载并保存到文件中。每个用户都保存在文件的新行中。我的问题是当我尝试使用 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");
}
答:
2赞
Andrew Henle
12/5/2016
#1
此代码是错误的:
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 ) {
...
你在一条线上做的越多,你犯错误的可能性就越大。正确编程已经够难了。不要做一些让事情变得更难的事情——比如试着看看你能在一行中塞进多少代码。
评论
0赞
MD XF
12/5/2016
这是不必要的;您可以简单地编写,因为它基本上会自动与 0 进行比较。( NULL == f )
(f)
0赞
Armando Andres Flores
12/5/2016
谢谢!我试过分 2 行做,但那次我肯定误解了结果。至少这让我加强了优先权的重要性!!
0赞
Andrew Henle
12/5/2016
@MDXF “这是不必要的;你可以简单地写成“等价于。现在你明白为什么我倾向于实际进行比较了。( NULL == f )
(f)
( NULL == f )
( !f )
NULL
评论