sw_perf/get_line.c

61 lines
1.8 KiB
C

/*********************************************************************************************
Description: Get specific line of a txt file
Copyright : All right reserved by NCIC.ICT
Author : Zhang Zhonghai
Date : 2023/08/28
***********************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define READ_BUF_SIZE 102400000
int main(int argc, char *argv[])
{
if (argc < 3)
{
fprintf(stderr, "Please input the file path and the line number you want to get!\n");
return 1;
}
const char *in_path = argv[1];
size_t expect_line_num = atoi(argv[2]);
FILE *in_f = fopen(in_path, "r");
char *read_buf = (char *)malloc(READ_BUF_SIZE);
int actual_size = 0;
int expect_size = READ_BUF_SIZE;
size_t cur_line_num = 0;
size_t last_line_pos = 0;
size_t cur_line_pos = 0;
int i, j;
int flag_found = 0;
// 读取数据
actual_size = fread(read_buf, 1, expect_size, in_f);
while (actual_size > 0)
{
for (i = 0; i < actual_size; ++i)
if (read_buf[i] == '\n')
{
cur_line_num += 1;
last_line_pos = cur_line_pos;
cur_line_pos = i;
if (cur_line_num == expect_line_num)
{
for (j = last_line_pos + 1; j <= cur_line_pos; ++j)
{
fprintf(stdout, "%c", read_buf[j]);
}
flag_found = 1;
break;
}
}
if (flag_found)
break;
actual_size = fread(read_buf, 1, expect_size, in_f);
}
if (!flag_found)
fprintf(stderr, "Invalid line number!\n");
return 0;
}