You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言对CSV文件首列按字母排序并跳过表头?

提取CSV首列并按字母排序的C语言实现

需求说明

现有如下CSV格式的数据文件,需要实现一个C程序完成以下操作:

  • 跳过表头行
  • 提取每行的第一列(Location 1字段)
  • 将提取的内容按字母顺序排序后输出

CSV文件内容

Location 1,Location 2,Price,Rooms,Bathrooms,CarParks,Type,Area,Furnish
Upper-East-Side,New-York,310000,3,2,0,Built-up,1000,Partly
West-Village,New-York,278000,2,2,0,Built-up,1000,Partly
Theater-District,New-York,688000,3,2,0,Built-up,1000,Partly

预期输出

Theater-District
Upper-East-Side
West-Village

现有代码(仅读取展示内容)

#include <stdio.h>

int main()
{
  FILE *fh;
  
  fh = fopen("file.csv", "r");
  
  if (fh != NULL)
  {
    int line_number = 0;
    char c;
    while ( (c = fgetc(fh)) != EOF )
    {
        if(line_number > 0 || c == '\n'){
            putchar(c);
        }
        if(c == '\n'){
            line_number++;
        }
    }
    fclose(fh);
  
  } else printf("Error opening file.\n");
  
  return 0;
}

解决方案代码

以下是实现需求的完整代码,核心步骤包括跳过表头、提取首列、存储字符串、排序输出:

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

#define MAX_LOCATIONS 100  // 根据实际数据量调整
#define MAX_LINE_LEN 256

// qsort的比较函数,按字符串字典序排序
int compare_strings(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

int main() {
    FILE *fh = fopen("file.csv", "r");
    if (!fh) {
        printf("Error opening file.\n");
        return 1;
    }

    char line[MAX_LINE_LEN];
    char *locations[MAX_LOCATIONS];
    int count = 0;

    // 跳过表头行
    if (!fgets(line, MAX_LINE_LEN, fh)) {
        fclose(fh);
        return 1;
    }

    // 读取剩余行,提取首列
    while (fgets(line, MAX_LINE_LEN, fh) && count < MAX_LOCATIONS) {
        // 找到第一个逗号的位置
        char *comma_pos = strchr(line, ',');
        if (comma_pos) {
            // 截断字符串到逗号前
            *comma_pos = '\0';
            // 去除换行符(如果存在)
            char *newline_pos = strchr(line, '\n');
            if (newline_pos) {
                *newline_pos = '\0';
            }
            // 分配内存存储字符串
            locations[count] = malloc(strlen(line) + 1);
            if (locations[count]) {
                strcpy(locations[count], line);
                count++;
            }
        }
    }

    fclose(fh);

    // 对字符串数组排序
    qsort(locations, count, sizeof(char *), compare_strings);

    // 输出排序后的结果
    for (int i = 0; i < count; i++) {
        printf("%s\n", locations[i]);
        free(locations[i]);  // 释放内存
    }

    return 0;
}

代码说明

  1. 跳过表头:用fgets读取第一行后直接丢弃,不做处理
  2. 提取首列:对每行用strchr定位第一个逗号,截断字符串并去除末尾换行符
  3. 存储字符串:为每个提取的字符串分配独立内存,避免覆盖
  4. 排序:使用标准库qsort函数,配合自定义字符串比较函数实现字典序排序
  5. 内存管理:排序输出后释放分配的内存,避免内存泄漏

内容的提问来源于stack exchange,提问作者Juju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:55:19