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

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

问题描述

什么是阅读文本文件到动态一维数组的最有效的方法?每次读一个char之后reallocing似乎傻了,每次读行后reallocing似乎并没有要好得多。我想整个文件读入的阵列。你会怎么做呢?

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在实际code 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天全站免登陆