linux - 我怎样才能安全而简单地从文件或标准输入中读取一行文本?

标签 linux scanf readline fgets fgetc

鉴于 fgets 有时只包含一个换行符,而 fscanf 本质上是不安全的,我想要一个简单的替代方法来从文件中逐行读取文本。此页面是找到此类功能的好地方吗?

最佳答案

是的。以下功能应满足此要求,而不会产生任何破坏性的安全漏洞。

/* reads from [stream] into [buffer] until terminated by
 * \r, \n or EOF, or [lastnullindex] is reached. Returns
 * the number of characters read excluding the terminating
 * character. [lastnullindex] refers to the uppermost index
 * of the [buffer] array. If an error occurs or non-text
 * characters (below space ' ' or above tilde '~') are
 * detected, the buffer will be emptied and 0 returned.
 */
int readline(FILE *stream, char *buffer, int lastnullindex) {
  if (!stream) return 0;
  if (!buffer) return 0;
  if (lastnullindex < 0) return 0;
  int inch = EOF;
  int chi = 0;
  while (chi < lastnullindex) {
    inch = fgetc(stream);
    if (inch == EOF || inch == '\n' || inch == '\r') {
      buffer[chi] = '\0';
      break;
    } else if (inch >= ' ' && inch <= '~') {
      buffer[chi] = (char)inch;
      chi++;
    } else {
      buffer[0] = '\0';
      return 0;
    }
  }
  if (chi < 0 || chi > lastnullindex) {
    buffer[0] = '\0';
    return 0;
  } else {
    buffer[chi] = '\0';
    return chi;
  }
}

关于linux - 我怎样才能安全而简单地从文件或标准输入中读取一行文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23621090/

相关文章:

c - 一旦在 C 中获得输入,就忽略该行的其余部分

c - 需要有关 C 中函数 scanf 的帮助

linux - bat to sh 翻译请

linux - 如何检查文件夹是否为空或文件夹文件是否使用 shell 脚本?

linux - 读取file.sql并创建数据库

python - 以编程方式中断 raw_input

c - 在 ansi c 中用 pascal 替换 readln 有什么很酷的功能吗?

linux - 使用java启动远程进程

c - 出现一个额外的输入

bash/readline 相当于 vi 模式下的转义点