buffer的按行分割实现

发布时间 2023-04-26 10:49:31作者: eiSouthBoy

一、问题引入

在处理文件过程中,一般流程是:open file --> read file to buffer --> parse buffer --> close file

文件处理单元是一行,故需要将 buffer 内容按行解析,本文就是说明这个问题。

二、解决过程

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

#define ERROR -1
#define OK     0

#define MAX_LINES    100 // 定义最大行数
#define LINE_LEN_MAX 300 // 定义每行最大长度

int line_parse(const char buffer[], int buffer_len, char line_list_array[][LINE_LEN_MAX], int *num_of_lines)
{
    int i = 0;
    char *p_buf = (char *)malloc(buffer_len + 1);
    if (p_buf == NULL)
        return ERROR;
    memset(p_buf, 0, buffer_len + 1);
   memcpy(p_buf, buffer, buffer_len);
    // make sure the end character of string that is '\n'
    if(p_buf[buffer_len-1] != '\n')
        p_buf[buffer_len] = '\n';
    int buf_len = strlen(p_buf);
    const char *p_start = p_buf;
    const char *p_end = memchr(p_start, '\n', buf_len);
    while (p_end != NULL && i < MAX_LINES)
    {
        memmove(line_list_array[i++], p_start, p_end - p_start);
        buf_len = buf_len - (p_end - p_start + 1);
        p_start = p_end + 1;
        p_end = memchr(p_start, '\n', buf_len);
    }
    *num_of_lines = i;
    free(p_buf);
    return OK;
}

int main()
{
    char buffer[] = {"hello world\nwelcome to china\n"};
    char line_list_array[MAX_LINES][LINE_LEN_MAX] = {0};
    int buffer_len = strlen(buffer);
    int num_of_lines = 0;
   
    line_parse(buffer, buffer_len, line_list_array, &num_of_lines);
    for (int i = 0; i < num_of_lines; i++)
    {
        printf("%s\n", line_list_array[i]);
    }

    return 0;
}

? 运行结果

  • 修改buffer
char buffer[] = {"hello world\nwelcome to china"};

? 运行结果

三、反思总结

buffer传入的末尾不一定包含回车字符 \n,故解析时要考虑这种情形

// make sure the end character of string that is '\n'
if(p_buf[buffer_len-1] != '\n')
    p_buf[buffer_len] = '\n';

四、参考引用