如何在C中将文件内容读取为字符串? [英] How to read the content of a file to a string in C?

查看:44
本文介绍了如何在C中将文件内容读取为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用 C 语言打开文件并将其内容读入字符串(char*、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.

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

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