现在的位置: 首页 > 综合 > 正文

setbuf函数使用注意事项 setbuf函数使用注意事项ungetc()函数的用法

2017年12月12日 ⁄ 综合 ⁄ 共 1626字 ⁄ 字号 评论关闭
 

setbuf函数使用注意事项

分类: c 85人阅读 评论(0) 收藏 举报
C

程序输出有两种方式:一种是即时处理方式,另一种是先暂存起来,然后再大块写入的方式,前者往往造成较高的系统负担。因此,c语言实现通常都允许程序员进行实际的写操作之前控制产生的输出数据量。

这种控制能力一般是通过库函数setbuf实现的。如果buf是一个大小适当的字符数组,那么:

setbuf(stdout,buf);

语句将通知输入/输出库,所有写入到stdout的输出都应该使用buf作为输出缓冲区,直到buf缓冲区被填满或者程序员直接调用fflush(译注:对于由写操作打开的文件,调用fflush将导致输出缓冲区的内容被实际地写入该文件),buf缓冲区中的内容才实际写入到stdout中。缓冲区的大小由系统头文件<stdio.h>中的BUFSIZ定义

举例说明如下(代码通过VS2008编译)

#include <iostream>
#include<fstream>

int main(int argc, char* argv[])
{
    char* outbuf =  new char [100];
    setbuf(stdout,outbuf);//将输出流绑定到outbuf上
    puts("helloworld\n");//内容输入到outbuf内
    //setbuf(stdout,NULL);//如果启用这行代码,输出流恢复原来的状态,puts输出到控制台
    delete[] outbuf;
    system("pause");
    return 0;

}


 

ungetc()函数的用法

分类: c 89人阅读 评论(0) 收藏 举报

ungetc函数是将输出流中的废弃数据退入流中去。

MSDN是这样定义的

int ungetc(
   int c,
      FILE *stream 
);
Parameters
c Character to be pushed.
stream Pointer to FILE structure.
Return Value
If successful, each of these functions returns the character argument c. If c cannot be pushed back or if no character has been read, the input stream is unchanged and ungetc returns EOF; ungetwc returns WEOF. If stream is NULL, the invalid parameter handler is invoked, as described in Parameter Validation. If execution is allowed to continue,EOF or WEOF is returned and errno is set to EINVAL.


贴出实例代码:代码通过VS2008编译
/*************************************************************/
#include <iostream>
//#pragma  pack(4)
#include <cctype>




int main(int argc,char *argv[])
{
    int ch=0,sum=0;
    while ( ( ch=getchar() )!=EOF&&isdigit(ch) )
    {
        sum*=10;
        ch-='0';
        sum+=ch;
    }
    ungetc(ch,stdin);
    printf("%d\n",sum);
    fflush(stdin);
    system("pause");
    return 0;
}
/*******************************************************************/
输入:12345r
输出:12345

抱歉!评论已关闭.