简体   繁体   中英

fopen fprintf dosnt write to file only after closing it

how to enable the writing to file befor closing it , i have this code to write to file , is does it but only after i close the app and it gets to the distractor its part of simple logger. what i need is to see the write updates ( with tail -f )

void init(char *pfileName)
    {
        if(pfileName != NULL)
        {
            fp = fopen(pfileName, "a+");
            if(fp != NULL)
                fseek(fp, 0, SEEK_END);
        }
    }

    void close()
    {
        if(fp != NULL)
            fclose(fp);
        fp = NULL;
    }

void write(char *pType, std::string pMsg, char *pFileName, int lineNo)
    {
        if(fp != NULL)
        {
            fprintf(fp,"%s %s %s %s %d %s\n", pType, __DATE__, __TIME__, pFileName, lineNo, pMsg.c_str());

        }
    }

The IO is likely buffered. Insert fflush(fp) after your write.

Amadan is correct , a fflush(fp) would solve the problem for you.

But if you want to fix this issue everywhere you should instead use the setvbuf(3) function to put your specific FILE pointer into line-buffered mode. The C Standard IO streams support no buffering , line buffering , block buffering . By default, all files are block-buffered; standard output is line buffered when it is sent to the terminal, and standard error is unbuffered. You can change these defaults.

Add setlinebuf(fp); to your application immediately after the error checking for fp = fopen(...); and all your output to this FILE stream will be line-buffered.

This of course does bring with it the performance penalties of line buffering rather than block buffering, but people normally complain about this when their output is pretty slow anyway. (Otherwise the blocks would fill up quickly and be flushed quickly.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM