How to read data from a CSV file in the C language?

To read data from a CSV file in C language, you can follow these steps:

  1. Include the necessary header files:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  1. Create a structure to store each line of data in a CSV file.
typedef struct {
    char field1[100];
    char field2[100];
    // 可以根据需要添加更多的字段
} CSVData;
  1. Write a function to read data from a CSV file.
void readCSV(const char* filename, CSVData* data, int* num_rows) {
    FILE* file = fopen(filename, "r");
    if (file == NULL) {
        printf("无法打开文件。\n");
        return;
    }

    char line[256];
    int i = 0;

    while (fgets(line, sizeof(line), file)) {
        // 使用strtok函数按照逗号分隔每个字段
        char* token = strtok(line, ",");
        strcpy(data[i].field1, token);
        token = strtok(NULL, ",");
        strcpy(data[i].field2, token);
        // 可以根据需要继续读取更多的字段

        i++;
    }

    *num_rows = i;

    fclose(file);
}
  1. Use the above function to read data from the CSV file.
int main() {
    CSVData data[100];
    int num_rows;
    readCSV("data.csv", data, &num_rows);

    // 打印读取到的数据
    for (int i = 0; i < num_rows; i++) {
        printf("第 %d 行数据:\n", i+1);
        printf("字段1:%s\n", data[i].field1);
        printf("字段2:%s\n", data[i].field2);
        // 可以根据需要打印更多的字段
        printf("\n");
    }

    return 0;
}

The above code assumes that each row in the CSV file only has two fields, which can be adjusted according to the actual situation. Additionally, it is necessary to ensure that the CSV file exists and is in the correct format.

bannerAds