我開始代碼C.我的代碼如下:讀CSV文件導入結構陣列
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_LEN 256
#define MAX_BOOKS 256
struct book{
int ID;
char *name;
char *dateIn;
char *dateOut;
};
struct book books[MAX_BOOKS];
/* PROTOTYPE OF FUNCTIONS */
int readBookFile();
void printBookList();
int main(int argc, char **argv)
{
int isOK = 0;
isOK = readBookFile();
printBookList();
system("pause");
return 0;
}
int readBookFile()
{
/* FileStream for the Library File */
FILE *bookFile;
/* allocation of the buffer for every line in the File */
char *buf = malloc(MAX_STR_LEN);
char *tmp;
/* if the space could not be allocaed, return an error */
if (buf == NULL) {
printf ("No memory\n");
return 1;
}
if ((bookFile = fopen("library.dat", "r")) == NULL) //Reading a file
{
printf("File could not be opened.\n");
}
int i = 0;
while (fgets(buf, 255, bookFile) != NULL)
{
if ((strlen(buf)>0) && (buf[strlen (buf) - 1] == '\n'))
buf[strlen (buf) - 1] = '\0';
tmp = strtok(buf, ";");
books[i].ID = atoi(tmp);
tmp = strtok(NULL, ";");
books[i].name = tmp;
tmp = strtok(NULL, ";");
books[i].dateIn = tmp;
tmp = strtok(NULL, ";");
books[i].dateOut = tmp;
//tempBook.ID = atoi(buf);
printf("index i= %i ID: %i, %s, %s, %s \n",i, books[i].ID , books[i].name, books[i].dateIn , books[i].dateOut);
i++;
}
//free(buf);
fclose(bookFile);
return 0;
}
void printBookList()
{
int i;
//i = sizeof(books)/sizeof(books[0]);
//printf ("%i \n", i);
for (i = 0; i <= sizeof(books); i++)
{
if (books[i].ID != 0)
printf("index i= %i ID: %i, %s, %s, %s \n",i, books[i].ID , books[i].name, books[i].dateIn , books[i].dateOut);
else
break;
}
}
的問題是,readBookFile()結束後,我的結構的陣列是滿輸入文件的最後一個值..的
我的輸入文件是:
1;das erste Buch; 12122013; 13122013
2;das Zweite Buch; 12122013; 13122013
3;das dritte Buch; 12122013; 13122013
4;das vierte Buch; 12122013; 13122013
5;das fünfte Buch; 12122013; 13122013
6;das sechste Buch; 12122013; 13122013
所以在readBookFile功能的printf返回正確的價值觀,但在printBooksList()函數的所有值似乎有變成 我的輸入文件的最後一行。
誰能給我講解一下,也許指向我朝着正確的方向?
非常感謝 Hagbart