所以,我是C的新手,我正在尝试将.txt文件中的数据读入链表。我创建了一个插入函数,将.txt文件中的每个值放入列表中的一个节点。当我尝试打印出所有数据时,它只显示txt文件中的最后一个值。
例如: txt文件中有三个值。 当我尝试打印所有值时,它只打印第三个值,三次。
以下是代码:
#include "action.h"
void insert(ListPtr *ptr, arPtr *sPtr);
void printList( ListPtr ptr);
int main(void){
int i,num;
// initialize the file pointer
FILE *ptr;//Daily
FILE *PTR;//Group
ListPtr startPtr = NULL;
arPtr dataPtr;
dataPtr = (arPtr) malloc( sizeof( AR));
//dataPtr = {0,0,0,"",""};
//dataPtr = malloc(sizeof ( AR));
int choice = 0;
char groupFile[20];
char dailyFile[20];
dataPtr->location[2] = '\0';
dataPtr->id[6] = '\0';
// Step one: Ask the user what the group file is.
printf("What is the name of the Daily File you want to load?\nFile Name:\t");
scanf("%s",dailyFile);
/////////////////////////////////////////////////////////////////////////////////////////////
// Read from the group File
if((ptr = fopen(dailyFile,"r+")) == NULL){
printf("We could not find that Daily File, We will open a new file for you to work with.");
ptr = fopen(dailyFile,"w");
choice = 1;
}
else{
while(!feof(ptr)){
// fread(dataPtr,sizeof(struct ActionReport),1,ptr);
printf("Before Scanning");
fscanf(ptr, "%4d%6s%2s",&(dataPtr->startTime), dataPtr->id, dataPtr->location);
fgets(dataPtr->description,50,ptr);
// if (dataPtr != NULL){
printf("After Scanning\n\n");
//check the value that was read from the file
printf("%4d\t%6s\t%2s\t%10s",dataPtr->startTime,dataPtr->id,dataPtr->location,dataPtr->description);
insert(&startPtr,&dataPtr);
//check the value that was placed into the linked list
printf("%4d\t%6s\t%2s\t%10s",startPtr->ARdata->startTime,startPtr->ARdata->id,startPtr->ARdata->location,startPtr->ARdata->description);
}//end while
fclose(ptr);
}//elsei
printList(startPtr);