gpt4 book ai didi

c - 从 csv 文件读入二维数组并使用 c 对数组进行排序

转载 作者:行者123 更新时间:2023-11-30 21:00:06 24 4
gpt4 key购买 nike

在我的 csv 文件中,目前我有类似的数据

45454, 32, 78, C, 67
45452, 22, 38, C, 34

我想将数据添加到二维数组中并对其进行排序。目前我正在使用这种方法

#include<stdio.h>
#include<conio.h>
#include<String.h>

void getData(char *buff);
int main()
{
FILE *fp = fopen("file1.csv", "r");
int count = -1;
do
{
char buff[1024];
fgets(buff, 1024, (FILE*)fp);
count++;
if(count != 1)
{
printf(buff);
getData(buff);
}
}
while((getc(fp))!= EOF);


}
void getData(char buff[])
{
char *token = strtok(buff,",");
int counter=0;

while( token != NULL )
{
counter++;
printf(" %s\n",token);
token = strtok(NULL,",");
}
}

但我想使用 fgets 和 sscanf 读取数据并将它们存储到单维 VLA(可变长度数组)中我怎样才能做到这一点?

最佳答案

您实际上并不需要二维数组。你只需要一个数组来保存你的行。给你:

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

struct row {
int id;
int col1;
int col2;
char col3;
int col4;
};

int cmp(const void *a1, const void *a2) {
const struct row *r1 = a1;
const struct row *r2 = a2;
return r1->id - r2->id;
}

void line_to_row(char *buff, struct row *r)
{
char *saveptr;
char *token = strtok_r(buff, ",", &saveptr);
if (token == NULL) {
exit(1);
}
r->id = atoi(token);

token = strtok_r(buff, ",", &saveptr);
if (token == NULL) {
exit(1);
}
r->col1 = atoi(token);

token = strtok_r(buff, ",", &saveptr);
if (token == NULL) {
exit(1);
}
r->col2 = atoi(token);

token = strtok_r(buff, ",", &saveptr);
if (token == NULL) {
exit(1);
}

while (*token != '\0') {
r->col3 = *token;
token++;
}

r->col4 = atoi(buff + 1);
}

int main()
{
FILE *fp = fopen("file1.csv", "r");
if (fp == NULL) {
exit(1);
}
char buff[1024 + 1];
int c, i = 0, len = 10;
struct row *rows = malloc(sizeof(*rows) * len);
struct row *temp = rows;

while (fgets(buff, 1024, (FILE*)fp)) {
if (i == len - 1) {
len += 10;
temp = realloc(rows, sizeof(*rows) * len);
if (temp == NULL) {
exit(1);
}
rows = temp;
}
line_to_row(buff, &rows[i]);
i++;
}
fclose(fp);

if (i == 0) {
return 0;
}

len = i;
temp = realloc(rows, sizeof(*rows) * len);

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

rows = temp;

qsort(rows, len, sizeof(*rows), &cmp);

for (i = 0; i < len; i++) {
printf("%d\n", rows[i].id);
}
free(rows);
return 0;
}

关于c - 从 csv 文件读入二维数组并使用 c 对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com