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

C语言使用getline实现支持反斜杠续行的多行用户命令读取

问题分析

你的原有代码存在两个核心问题:

  1. 只调用了一次getline,所以只能读取单行输入,没有循环判断行尾反斜杠的逻辑
  2. char* line;未初始化为NULL,传入getline会触发未定义行为,大概率导致程序崩溃

实现思路

  • 维护一个动态扩容的结果缓冲区,存储最终拼接后的完整命令
  • 循环调用getline读取每一行,读取后先删除行尾的换行符
  • 判断当前行末尾是否为反斜杠:如果是则删除反斜杠,将当前行拼入结果后继续读下一行;如果不是则拼入当前行后结束读取
  • 做好内存管理,避免泄漏和野指针问题

修改后的完整代码

首先确保你引入了必要的头文件:

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

实现函数:

char *getCommand(void) {
    char *result = NULL;
    size_t result_len = 0;
    char *line = NULL;
    size_t line_cap = 0;
    ssize_t line_len;

    while (1) {
        line_len = getline(&line, &line_cap, stdin);
        // 处理读取失败/EOF情况
        if (line_len == -1) {
            free(line);
            if (feof(stdin)) {
                return result ? result : NULL;
            }
            fprintf(stderr, "Error reading the command: %s\n", strerror(errno));
            free(result);
            exit(EXIT_FAILURE);
        }

        // 移除行尾的换行符
        if (line_len > 0 && line[line_len - 1] == '\n') {
            line[line_len - 1] = '\0';
            line_len--;
        }

        int need_next_line = 0;
        // 判断是否需要继续读取下一行
        if (line_len > 0 && line[line_len - 1] == '\\') {
            need_next_line = 1;
            line[line_len - 1] = '\0'; // 删除末尾的反斜杠
            line_len--;
        }

        // 扩容结果缓冲区,拼接当前行内容
        result = realloc(result, result_len + line_len + 1);
        if (!result) {
            perror("memory allocation failed");
            free(line);
            exit(EXIT_FAILURE);
        }
        memcpy(result + result_len, line, line_len + 1);
        result_len += line_len;

        if (!need_next_line) {
            free(line);
            break;
        }
    }
    return result;
}

注意事项

  • 调用方获取到函数返回的字符串后,使用完毕必须调用free()释放内存,避免内存泄漏
  • 如果用户在输入末尾为反斜杠时触发EOF,函数会直接返回已拼接的内容,不会报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:48:04