分享

字符流相关函数

 海漩涡 2016-05-20
#include <stdio.h>

一、对一个字符的操作
       int fgetc(FILE *stream);

       int getc(FILE *stream);

       int getchar(void);

       int ungetc(int c, FILE *stream);
1、fgetc和getc最大的区别在前者是函数,后者是宏,getc由fgetc通过宏实现,调用的时候注意参数stream不能是有副作用的表达式

2、getchar() is equivalent to getc(stdin).

3、ungetc() pushes c back to stream,


二、对一个字符串的操作
       char *gets(char *s);

       char *fgets(char *s, int size, FILE *stream);

1、gets() 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 (see BUGS below).

warning: the `gets' function is dangerous and should not be used.

2、 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.
 




=================================================================


代码示例


#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#define MAX_BUF_LEN 1024

int main()
{
int len = -1;
char *buf = (char *)malloc(MAX_BUF_LEN);
if(NULL == buf)
{
perror("calloc error:\n");
return -1;
}
while(1)
{
// char *fgets(char *s, int size, FILE *stream);
// gets() and fgets() return s on success, and NULL on error or when end of file occurs while no characters have been read.
memset(buf, 0, MAX_BUF_LEN);
printf("Please input ->:");
fgets(buf, MAX_BUF_LEN, stdin);
len = strlen(buf);
buf[len - 1] = '\0';
printf("len[%d] out:%s\n", len, buf);
}

return 0;
}
       

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多