获得在C文件中的内容,最简单的方法 [英] Easiest way to get file's contents in C
本文介绍了获得在C文件中的内容,最简单的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是最简单的方法(最不容易出错,code的最小行,但是你要跨preT吧)开在C文件并阅读其内容为一个字符串(字符*,的char [],等等)?
What is the simplest way (least error-prone, least lines of code, however you want to interpret it) to open a file in C and read its contents into a string (char*, char[], whatever)?
推荐答案
我倾向于只加载整个缓冲区作为原料内存块到内存中,并做我自己的解析。这样,我有比标准库确实在多个平台上最擅长的控制。
I tend to just load the entire buffer as a raw memory chunk into memory and do the parsing on my own. That way I have best control over what the standard lib does on multiple platforms.
这是一个存根我用这个。您可能还需要检查错误 - codeS fseek的,FTELL和FREAD。 (省略清晰)。
This is a stub I use for this. you may also want to check the error-codes for fseek, ftell and fread. (omitted for clarity).
char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
if (buffer)
{
// start to process your data / extract strings here...
}
这篇关于获得在C文件中的内容,最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文