且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C中将文件的内容读取为字符串?

更新时间:2023-11-13 18:53:40

我倾向于将整个缓冲区作为原始内存块加载到内存中,然后自行解析.这样,我就可以***地控制标准库在多个平台上的功能.

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.

这是我用于此的存根.您可能还需要检查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...
}