Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fopen fprintf dosnt write to file only after closing it

Tags:

c

fopen

fwrite

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());

        }
    }
like image 568
user63898 Avatar asked Dec 13 '22 06:12

user63898


2 Answers

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

like image 135
Amadan Avatar answered Jan 04 '23 23:01

Amadan


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.)

like image 34
sarnold Avatar answered Jan 05 '23 01:01

sarnold