-
April 23rd, 2013, 06:10 PM
#1
Access violation when using pointers to read data
I have the following method to read in a data file using a struct and a doubly linked list.
The readFile method is as follows:
Code:
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';
}
sname = strtok(oneLine,",");
fname = strtok(NULL,",");
phone = strtok(NULL,",");
company = strtok(NULL,",");
email = strtok(NULL,",");
if(head == NULL)
{
head = (struct contact *)malloc(sizeof(struct contact));
*ptrList = head;
strcpy(head->sname,sname);
strcpy(head->fname,fname);
strcpy(head->phone,phone);
strcpy(head->company,company);
strcpy(head->email, email);
head->prev = NULL;
head->next = NULL;
}
else
{
head->next = (struct contact *)malloc(sizeof(struct contact));
head = head->next;
head->next = NULL;
//copy the data to the new one
strcpy(head->sname,sname);
strcpy(head->fname,fname);
strcpy(head->phone,phone);
strcpy(head->company,company);
strcpy(head->email,email);
}
}//end while
fclose(fptr);
return(head);
}
int writeListToFile(char * theFile, struct contact *theList)
{
struct contact * curr;
FILE *fptr;
fptr = fopen(theFile,"w");
if (fptr == NULL)
{
printf("\noops");
return(0);
}
fprintf(fptr, "Surname, FirstName, Phone, Company, Email");
curr = theList;
while(curr != NULL)
{
fprintf(fptr,"\n%s,%s,%s,%s,%s",curr->sname,curr->fname,curr->phone,curr->company,curr->email);
curr = curr->next;
}
fclose(fptr);
return(1);
}//end writeFileToList
My struct definition is like this:
Code:
struct contact {
char sname[15];
char fname[15];
char phone[15];
char company[15];
char email[15];
struct contact *prev;
struct contact *next;
};
Anyone know where I'm going wrong here?
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|