(转)fflush函数详解2

在有些时候,你会发现你的输出并没有按照你代码的流程输出, 比如说当你用C语言写了做了一个写文件的函数并印出一些信息,供perl或php等调用.而这时你会发现, perl或php并没有获取到你C语言中的打印信息.而代码什么都没有错误,在linux终端也可以正确打印出来. 这时可真是郁闷吧. 那么, 记住了, 这很大可能是没有更新你的缓冲区了. 这时int fflush(FILE *stream)这个函数就有用了. 下面看看这个函数的信息:

下面还是用例子来说明吧:

文件名: fflush.c

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

int writefile(char *filename, char *buf, int length)
{
    FILE *fp;
    int j = 0;
    size_t i = 0;
    fp = fopen(filename, "w");
    if (fp == NULL) {
        printf("\topen file error!\n");
        return -1;
    } else {
        while (length != 0) {
            i = fwrite(&buf[j], 1, 1, fp);
            length--;
            j ;
        }
    }
    fflush(fp);
    fclose(fp);
    return 0;
}

int readfile(char *filename, char *buf)
{
    FILE *fp;
    int j = 0;
    size_t i;
    fp = fopen(filename, "rb");
    if (fp == NULL) {
        printf("error\n");
        return -1;
    } else {
        while (1) {
            i = fread(&buf[j], 1, 1, fp);
            if (i == 0)
                break;
            j ;
        }
    }
    fflush(fp);
    fclose(fp);
    return 111;
}

int main(int argc, char **argv)
{
    char msg[128] = "hello,xiong feng!";
    char fbuf[1024] = "";
    char *filename = "/xiongfeng";
    int w_ret = 0;
    int r_ret = 0;

    w_ret = writefile(filename, msg, strlen(msg));
    if (w_ret < 0) {
        printf("Write file %s fail!\n", filename);
    }
    printf("msg:%s\n", msg);    // 如果在未加入fflush(fp), 该输出有可能不能正常输出,特别是在perl调用该程序时, perl不能获取该程序中的输出

    r_ret = readfile(filename, fbuf);
    if (r_ret < 0) {
        printf("Read file %s fail!\n", filename);
    }
    printf("fbuf:%s\n", fbuf);   // 这行同上面的: printf("msg:%s\n", msg);    
    return 0;
}

--------------------------------end-----------------------------------

我在网上还找了一些个封装了一次fflush的函数, 如下:

void flush(FILE *stream)
{
    int duphandle;

    /* flush the stream's internal buffer */
    fflush(stream);

    /* make a duplicate file handle */
    duphandle = dup(fileno(stream));

    /* close the duplicate handle to flush/
       the DOS buffer */
    close(duphandle);
}

用此函数来替代fflush也行,但我感觉在这时, 调用dup(), fileno()等函数没什么用.

下面是这两个函数的分析:

dup():

int dup(int handle);   
作用:复制一个文件句柄

--------------------------------end-----------------------------------

fileno():

范例:

fileno.c:

#include <stdio.h>

int main(int argc, char **argv)
{
    FILE *fp;
    int fd;
    fp = fopen("/xiongfeng", "r");
    fd = fileno(fp);
    printf("fd = %d\n", fd);
    fclose(fp);
    return 0;
}

运行结果: fd = 3

--------------------------------end-----------------------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值