博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

gets,fgets

Posted on 2023-03-13 05:59  乔55  阅读(32)  评论(0编辑  收藏  举报

gets

// gets详解

char* gets(char* str);
// reads a line from stdin into the buffer pointed to  by  s 
// until,either a terminating newline or EOF
// which it replaces with a null byte('\0'),
// No check for buffer overrun is performed

// 从stdin读取一行保存至s指向的空间,直至遇到一个换行符\n或EOF
// 用\0取代换行符或EOF存至s
// 并不检查缓冲区溢出(即不检测s指向空间是否溢出)
// 特点:可以读取带空格的字符,scanf不可以读取带分隔符(空格,tab,回车换行)的字符串

// fgets() return s on success and
// NULL on error or when end of file occurs while no characters have been read
// 成功返回s地址,错误或没有读取到字符时返回NULL

// 举例
void test()
{
    char str[10];
    gets(str);
    printf("%s\n", str);
    printf("hello world\n");
}
// 测试1:
// 输入:123456789
// 输出:123456789
//      hello world
// 说明gets从stdin读取完一行数据后,会在str末尾添加字符串尾0标志

// 测试2:
// 输入:1234567890
// 输出:vs环境下,程序崩溃,错误信息如下
// 0x00BC2A8A 处有未经处理的异常(在 01-测试.exe 中): 堆栈 Cookie 检测代码检测到基于堆栈的缓冲区溢出。
// 输出:linux环境下,有段错误:Segmentation fault (core dumped)
// 2个环境下都会将你输入的内容原样输出,输出后系统崩溃,告诉你出错了

fgets

// fgets详解

char* fges(char* s,int size,FILE* stream);
// fgets() reads in at most one less than size characters from stream  
// and stores  them  into  the buffer pointed to by s.  
// Reading stops after an EOF or a newline.  
// If a newline is read, it is stored into the  buffer.
// A terminating null  byte('\0') is stored after the last character in the buffer

// 从stream指向的流中读取最多size-1个字符,并将其保存至s指向的缓冲区中
// 当读取了size-1个字符、当读到流末尾、当读到换行符时,结束读取。
// 且若读取到换行符,将换行符同样保存至s末尾。再为s指向空间添加尾0标志

// fgets() return s on success and
// NULL on error or when end of file occurs while no characters have been read
// 成功返回s地址,错误或没有读取到字符时返回NULL

// fgets结束读取的情况
#define N 5
char buf[N];
fgets(buf,N,stream);

// 设stram指向的文件中有abcd这一行内容
// 请问要读取几次才能把该内容读取完?答案:2次
// 第1次读取:a b c d '\0'
// 第2次读取:'\n' '\0'