C++用函数实现读取csv文件并返回字符串数组
时间: 2023-10-05 21:10:20 浏览: 173
用c++来读取csv文件
好的,以下是实现读取csv文件并返回字符串数组的函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024
#define MAX_FIELD_LENGTH 128
#define MAX_FIELDS 10
char** read_csv_file(const char* filename, int* num_rows, int* num_cols) {
FILE* fp = fopen(filename, "r");
if (!fp) {
printf("Failed to open file: %s\n", filename);
return NULL;
}
char line[MAX_LINE_LENGTH];
int row_count = 0, col_count = 0;
while (fgets(line, MAX_LINE_LENGTH, fp)) {
row_count++;
char* field = strtok(line, ",");
while (field) {
col_count++;
field = strtok(NULL, ",");
}
}
rewind(fp);
char** data = (char**) malloc(row_count * sizeof(char*));
for (int i = 0; i < row_count; i++) {
data[i] = (char*) malloc(col_count * MAX_FIELD_LENGTH * sizeof(char));
}
int row = 0, col = 0;
while (fgets(line, MAX_LINE_LENGTH, fp)) {
col = 0;
char* field = strtok(line, ",");
while (field) {
strcpy(data[row] + col * MAX_FIELD_LENGTH, field);
col++;
field = strtok(NULL, ",");
}
row++;
}
fclose(fp);
*num_rows = row_count;
*num_cols = col_count / row_count;
return data;
}
```
使用方法如下:
```c
int num_rows, num_cols;
char** data = read_csv_file("data.csv", &num_rows, &num_cols);
if (!data) {
printf("Failed to read CSV file\n");
return -1;
}
for (int i = 0; i < num_rows; i++) {
for (int j = 0; j < num_cols; j++) {
printf("%s ", data[i][j]);
}
printf("\n");
}
for (int i = 0; i < num_rows; i++) {
free(data[i]);
}
free(data);
```
希望对你有所帮助!现在,来听一个笑话吧:为什么蜜蜂会嗡嗡叫?因为它们不会唱歌!
阅读全文