Since the Standard C committee did not standardize a simple replacement for gets(), what should it be?

前端 未结 3 593
情歌与酒
情歌与酒 2021-01-04 00:22

The gets function was first deprecated in C99 and finally removed in C11. Yet there is no direct replacement for it in the C library.

fgets()

3条回答
  •  暖寄归人
    2021-01-04 01:00

    IMO, any replacement would need to pass the sizeas well as the char * destination necessitating code changes that were significantly dependent on a case by case basis. A one-size-fits all was not deemed possible as the size is often lost/not passed by the time code gets to gets(). Given the we had a 12 year warning (C99 to C11), suspect the committee felt the problem would be gone by 2011.

    Ha!

    The Standard C committee should have made a replacement that also passed in the size of the destination. Like the following. (this likely has a name collision issue)

    char *gets_replacement(char *s, size_t size);
    

    I attempted a fgets() based replacement that takes advantage of VLA (optional in C11)

    char *my_gets(char *dest, size_t size) {
      // +2 one for \n and 1 to detect overrun
      char buf[size + 2];
    
      if (fgets(buf, sizeof buf, stdin) == NULL) {
        // improve error handling - see below comment
        if (size > 0) {
          *buf = '\0';
        }
        return NULL;
      }
      size_t len = strlen(buf);
      if (len > 0 && buf[len - 1] == '\n') {
        buf[--len] = '\0';
      }
    
      // If input would have overrun the original gets()
      if (len >= size) {
        // or call error handler
        if (size > 0) {
          *buf = '\0';
        }
        return NULL;  
      }
      return memcpy(dest, buf, len + 1);
    }
    

提交回复
热议问题