C语言中gets、fgets以及fputs函数

本文介绍了C语言中不安全的gets函数及其潜在风险,推荐使用fgets函数进行字符串读取。fgets函数可以从流中读取字符并将其存储为C字符串,直到达到指定长度或遇到换行符或文件结束。它会在读取的字符串末尾自动添加空字符以标记字符串结束。
摘要由CSDN通过智能技术生成

1. gets函数

gets函数是不安全的,不推荐使用。如下代码:

#include <stdio.h>

int  main(void)
{   
    char name[5];                                                                                   
    gets(name);
    puts(name);

    return 0;
}

编译运行:


由此看到编译器给出的警告信息:使用gets函数是不安全的,不推荐使用。


再运行一次,输入较多字符时:


gets不检查预留存储区是否能够容纳实际输入的数据。多出来的字符简单的溢出到相邻的存储区,可能会导致错误。


2. fgets函数

(1)函数原型:

char * fgets ( char * str, int num, FILE * stream );


(2)函数说明:

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the End-of-File is reached, whichever comes first.
A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值