简体   繁体   中英

How can I safely and simply read a line of text from a file or stdin?

Given that fgets only sometimes includes a linebreak, and fscanf is inherently unsafe, I would like a simple alternative to read text line-by-line from a file. Is this page a good place to find such a function?

Yes. The following function should satisfy this requirement without creating any damaging security flaws.

/* 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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM