【问题标题】:How to change the gets() code to fgets()? [duplicate]如何将gets() 代码更改为fgets()? [复制]
【发布时间】:2020-12-13 14:34:34
【问题描述】:

在此代码中将gets 函数替换为fgets。编译程序。程序是否包含错误?如果是,请解释错误并修复代码。有人可以帮我吗?谢谢。

#include <stdio.h>
int main(int argc, char **argv){
char buf[7]; // buffer for seven characters
gets(buf); // read from stdio (sensitive function!)
printf("%s\n", buf); // print out data stored in buf
return 0; // 0 as return value
}

【问题讨论】:

标签: c linux compilation syntax-error fgets


【解决方案1】:

查找 fgets 的一些文档,

声明

char *fgets(char *str, int n, FILE *stream)

参数

  • str - 这是指向存储读取的字符串的字符数组的指针。
  • n - 这是要读取的最大字符数(包括最后的空字符)。通常,使用作为 str 传递的数组的长度。
  • stream - 这是指向 FILE 对象的指针,该对象标识从中读取字符的流。

所以不同之处在于我们需要提供流(在本例中为 stdin aka 输入)和要从 stdin 读取的字符串的长度。

以下应该有效:

#include <stdio.h>

#define BUFLEN 7

int main(int argc, char **argv) {
  char buf[BUFLEN]; // buffer for seven characters
  fgets(buf, BUFLEN, stdin); // read from stdio
  printf("%s\n", buf); // print out data stored in buf
  return 0; // 0 as return value
}

【讨论】:

    【解决方案2】:

    不同的是:

    • 您传递缓冲区的长度,以避免写入缓冲区末尾(您想要的)
    • fgets'\n' 留在缓冲区中,因此您必须手动将其删除。更准确地说,缓冲区末尾的 '\n' 表示该行可以放入缓冲区 - 这是处理比缓冲区长的行的方法。

    这是一个可能的代码(对长线没有特殊处理):

    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char **argv) {
        char buf[7]; // buffer for seven characters
        if (NULL == fgets(buf, sizeof(buf), stdin)) { // read from stdio (sensitive function!)
            buf[0] = '\0';    // test end of file of read error and says empty data
        }
        else {
            size_t ix = strcspn(buf, "\n"); // remove an optional '\n'
            buf[ix] = '\0';
        }
        printf("%s\n", buf); // print out data stored in buf
        return 0; // 0 as return value
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-06
      • 2015-04-08
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      • 2020-03-09
      • 1970-01-01
      相关资源
      最近更新 更多