从文本文件在C时的读数CSV [英] Reading CSV from text file in C

查看:113
本文介绍了从文本文件在C时的读数CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从C的文本文件中的文本文件格式是读CSV

I'm trying to read CSV from a text file in C. The text file format is

1,Bob,bob@gmail.com
2,Daniel,daniel@gmail.com
3,John,john@gmail.com

当我运行程序,数字显示正常,但姓名和电子邮件被显示为乱码。这是我的计划...

When I run the program, the number displays fine but the name and email are being displayed as garbage. Here is my program...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int number;
    char* name;
    char* email;
} Owner;

Owner owners[100];

int load(char* filename)
{
    char buffer[200];
    char token[50];
    Owner* owner;
    int owners_size = 0;
    FILE* file = fopen(filename, "r");

    while(fgets(buffer, 200, file) != NULL)
    {
        owner = (Owner*)malloc(sizeof(Owner));
        owner->number = atoi(strtok(buffer, ","));
        owner->name = strtok(NULL, ",");
        owner->email = strtok(NULL, ",");
        owners[owners_size++] = *owner;
    }

    fclose(file);
    return owners_size;
}

int main()
{
    int choise, owners_size, index;
    char* owners_filename = "owners2.txt";

    owners_size = load(owners_filename);

    if(owners_size)
    {
        printf("owners size: %d\n\n", owners_size);

        for(index = 0; index < owners_size; index++)
            printf("%d, %s %s\n", owners[index].number, owners[index].name, owners[index].email);
    }
}

谁能告诉我是什么原因。我AP preciate你的帮助。

Can anyone tell me what the reason is. I appreciate your help.

推荐答案

您只需指针存储到本地缓冲区。当你离开负荷()缓存不见了,无法访问了。

You just stored pointers into a local buffer. When you leave load() this buffer is gone and not accessible anymore.

您必须为名称分配内存和电子邮件之前,你可以把它复制到业主结构。

You must allocate memory for name and email before you can copy it into the Owner struct.

char *tok;
tok = strtok(NULL, ",");
len = strlen(tok);
owner->name = malloc(len + 1);
strcpy(owner->name, tok);
...

这篇关于从文本文件在C时的读数CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆