繁体   English   中英

如何读取 C 中的 CSV 文件

[英]How to read a CSV file in C

我正在尝试读取以下格式的 CSV 文件:

5,455,78,5
12245,4,78
1,455,4557,1,8,9

我设法打开了文件,但我不知道如何解释数据。 所有数据都写在第一列,但我不知道有多少行或每行有多少条目。 这是我打开文件的代码。

printf("File chosen is: %s",file);

int p=0;

FILE *myFile = NULL;

myFile = fopen(file,"r");

if (myFile == NULL)
{
    exit(1);
}

if (myFile != NULL)
{
    printf("\n\nFile read succesfully");
}

这应该解析您的 csv。 打开文件后,使用fgets读取每一行。 循环直到 fgets 返回 NULL ,这表明无法读取任何行并且您已到达文件末尾。 使用strtok从 fgets 解析您的行,使用逗号作为分隔符。

#include <stdio.h>  // file handling functions
#include <stdlib.h> // atoi
#include <string.h> // strtok

...

    char buffer[80];
    while (fgets(buffer, 80, myFile)) {
        // If you only need the first column of each row
        char *token = strtok(buffer, ",");
        if (token) {
            int n = atoi(token);
            printf("%d\n", n);
        }

        // If you need all the values in a row
        char *token = strtok(buffer, ",");
        while (token) { 
            // Just printing each integer here but handle as needed
            int n = atoi(token);
            printf("%d\n", n);

            token = strtok(NULL, ",");
        }
    }

...

感谢您发布一些代码,但您没有提及您在读入数据后希望如何处理数据。

我给你一些指点:

使用已知大小的数组从文件中读取数据并将其缓冲以进行处理。 循环运行它。 例如

  char buffer[1000];

  while (fgets(buffer, sizeof (buffer), myFile))
  {
    char *data = strtok(buffer, ",");

    printf("Data %s\n", data);
    /* Further processing of data */

    data = strtok(NULL, ",");

  }

  fclose(myFile);

使用strtok处理该缓冲区以分离出您的字符串。 令牌是数据分隔符,应该是','但我不清楚你是否也有换行符,但它需要保持一致。

处理上面返回的字符串。

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

const char* getfield(char* line, int num)
{
    const char* tok;
    for (tok = strtok(line, ",");
        tok && *tok;
        tok = strtok(NULL, ",\n"))
    {
        if (!--num)
            return tok;
    }
    return NULL;
}

int main()
{
    FILE *stream = fopen("yourfile.csv", "r");
    int i = 0;
    int j = 0;
    printf("Choose a line to be given its elements: ");
    scanf("%d", &j);
    char line[1024];
    while (fgets(line, 1024, stream))
    {
        char* tmp = _strdup(line);
        i++;
        printf("Element %d would be %s\n", i, getfield(tmp, j));
        free(tmp);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM