将文本文件读入 c 中的数组 [英] reading a text file into an array in c

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

问题描述

将文本文件读入动态一维数组的最有效方法是什么?在每次读取字符后重新分配似乎很愚蠢,在每次读取行后重新分配似乎也好不到哪里去.我想将整个文件读入数组.你会怎么做?

What would be the most efficient method of reading a text file into a dynamic one-dimensional array? reallocing after every read char seems silly, reallocing after every read line doesn't seem much better. I would like to read the entire file into the array. How would you do it?

推荐答案

我不太明白你想要什么.您是否要逐步处理文件,从中读取一行,然后放弃它并处理下一行?还是要将整个文件读入缓冲区?如果你想要后者,我认为这是合适的(在真实代码中检查 malloc 和 fopen 的 NULL 返回,以确定文件是否存在以及你是否有足够的内存):

I don't understand quite what you want. Do you want to incrementally process the file, reading one line from it, then abandon it and process the next? Or do you want to read the entire file into a buffer? If you want the latter, I think this is appropriate (check for NULL return for malloc and fopen in real code for whether the file exist and whether you got enough memory):

FILE *f = fopen("text.txt", "rb");
fseek(f, 0, SEEK_END);
long pos = ftell(f);
fseek(f, 0, SEEK_SET);

char *bytes = malloc(pos);
fread(bytes, pos, 1, f);
fclose(f);

hexdump(bytes); // do some stuff with it
free(bytes); // free allocated memory

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

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