curr
我有以下方法可以将文件读入结构,但是,由于变量为空,程序在到达写入文件方法时正在轰炸。
当变量被标记时,我添加了一个空检查,但此时它没有引发错误。我猜这与我将数据复制到的方式有关,newContact
但我看不出我在哪里搞砸了。
这是提到的方法,在文件中读取标记变量并添加newContact
:
struct contact *readFile(char * FName,struct contact** ptrList)
{
struct contact *head, *newContact;
FILE *fptr;
char oneLine[60];
char *sname, *fname, *phone,*company, *email;
head = *ptrList;
fptr = fopen(FName,"r");
if(fptr == NULL)
{
printf("\nCant open file!");
return(ptrList);
}
fgets(oneLine, 55, fptr);
while(!feof(fptr))
{
fgets(oneLine, 55, fptr);
if(oneLine[strlen(oneLine)-1] == '\n')
{
oneLine[strlen(oneLine)-1] = '\0';
}
// open file and other stuff
if(!ptrList) return; // invalid pointer
for(head=*ptrList;head&&head->next;head=head->next);
while( ReadLine(fptr,oneLine) )
{
//check that variables aren't empty here:
if(sname == NULL || fname == NULL)
{
printf("\nvariable empty!");
//return(ptrList);
}
sname = strtok(oneLine,",");
fname = strtok(NULL,",");
phone = strtok(NULL,",");
company = strtok(NULL,",");
email = strtok(NULL,",");
newContact = (struct contact *)malloc(sizeof(struct contact));
if(!newContact) break; // out of memory
newContact->prev = head;
newContact->next = 0;
//copy the data to the new one
strcpy(newContact->sname,sname);
strcpy(newContact->fname,fname);
strcpy(newContact->phone,phone);
strcpy(newContact->company,company);
strcpy(newContact->email,email);
head = newContact;
if(!*ptrList) *ptrList = head; // see: point 2
}
}
这是struct
声明:
struct contact {
char sname[15];
char fname[15];
char phone[15];
char company[15];
char email[15];
struct contact *prev;
struct contact *next;
};
我在这里也收到了一个未定义的错误ReadLine
。是否有我应该为此功能导入的库(因为我在搜索中看不到任何提及)?
while( ReadLine(fptr,oneLine) )
新的错误发生在这里:
head = *ptrList;
关于为什么要轰炸的任何想法?