将文本文件读入 C 中的行数组 [英] Reading text file into an array of lines in C

查看:48
本文介绍了将文本文件读入 C 中的行数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 C 我想以这样一种方式读入文本文件的内容,以便在完成所有工作后获得一个字符串数组,其中第 n 个字符串代表文本文件的第 n 行.文件的行可以任意长.

Using C I would like to read in the contents of a text file in such a way as to have when all is said and done an array of strings with the nth string representing the nth line of the text file. The lines of the file can be arbitrarily long.

实现此目的的优雅方式是什么?我知道一些巧妙的技巧可以将文本文件直接读入一个适当大小的缓冲区,但将其分成几行会使它变得更棘手(至少据我所知).

What's an elegant way of accomplishing this? I know of some neat tricks to read a text file directly into a single appropriately sized buffer, but breaking it down into lines makes it trickier (at least as far as I can tell).

非常感谢!

推荐答案

将其分解成行意味着解析文本并将所有 EOL(EOL 我的意思是 \n 和 \r)字符替换为 0.通过这种方式,您实际上可以重用缓冲区并将每一行的开头存储到单独的 char * 数组中(只需执行 2 遍即可).

Breaking it down into lines means parsing the text and replacing all the EOL (by EOL I mean \n and \r) characters with 0. In this way you can actually reuse your buffer and store just the beginning of each line into a separate char * array (all by doing only 2 passes).

通过这种方式,您可以对整个文件大小+2 次解析进行一次读取,这可能会提高性能.

In this way you could do one read for the whole file size+2 parses which probably would improve performance.

这篇关于将文本文件读入 C 中的行数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆