解析csv文件,填充struct并写入二进制数据文件

时间:2015-07-29 23:30:49

标签: c parsing csv struct

我正在尝试读取csv文件并解析它,然后填充结构以写入二进制.dat文件,此刻我陷入困境。我正在尝试创建10个.csv文件列表,这里是csv文件格式的示例: 1001,Shannon,Rylie,5824.12,1500.00

这是我的代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

#define MAXBUFSIZE 511
#define LOOPNUMBER 30
#define BUFFER_SIZE 1024

typedef struct{
int     accountNumber;
char    firstName[MAXBUFSIZE + 1];
char    lastName[MAXBUFSIZE + 1];
double  accountBalance;
double  lastPaymentAmount;
} accounts;

int main(void){

    int i;
    char buf[1024];
    const char* tok;

    accounts myarray[10];

    FILE    *fpData;

accounts temp = { 0, "", "", 0.0, 0.0 };

if ((fpData = fopen("accounts.csv", "r")) == NULL) //Reading a file
{
    printf("File could not be opened.\n");
}

while (fgets(buf, BUFFER_SIZE, fpData) != NULL)
{
    /* Here we tokenize our string and scan for " \n" characters */

    // for(tok = strtok(buf,"\n");tok;tok=strtok(NULL,"\n"))
    // {
    tok = strtok(buf, ",");
    temp.accountNumber = atoi(tok);
    printf(" %i ", temp.accountNumber);

    tok = strtok(NULL, ",");
    strncopy(temp.firstName, tok, MAXBUFSIZE);
    temp.firstName[MAXBUFSIZE] = '\0';

    tok = strtok(NULL, ",");
    strncopy(temp.lastName, tok, MAXBUFSIZE);
    temp.lastName[MAXBUFSIZE] = '\0';

    tok = strtok(NULL, ",");
    temp.accountBalance = atof(tok);
    printf("temp.accountBalance = %.2f ", temp.accountBalance);

    tok = strtok(NULL, ",");
    temp.lastPaymentAmount = atof(tok);
    printf("temp.lastPaymentAmount = %.2f ", temp.lastPaymentAmount);

    tok = strtok(NULL, ",");
    printf("\n");

    memcpy(&myarray[LOOPNUMBER], &temp, sizeof(accounts));
}

if ((fpData = fopen("accounts.dat", "wb")) == NULL)
{
    printf("File could not be opened.\n");
}
else
{
    for (i = 0; i < 10; i++)
    {
        fwrite(myarray, sizeof(accounts), 10, fpData);
    }
}

fclose(fpData);
}

1 个答案:

答案 0 :(得分:0)

这是一个简短的答案,你真的需要检查你的代码,那里有太多的strtoks。

但主要问题在于......我已经获得了片段并更改了fwrite - 请查看。

if ((fpData = fopen("accounts.dat", "wb")) == NULL)
{
    printf("File could not be opened.\n");
}
else
{
    for (i = 0; i < 10; i++)
    {
        fwrite( &myarray[ i ], sizeof(accounts), 1, fpData );
    }
}