Feb
11

How to change the buffering option for any specified stream in c programming?

Author JIGAR PATEL    Category c, Tips     Tags

Many of  us faced this problem. Sometimes we put some debug prints in our code this way

fprintf(logfile,"successfully reached at debug-point 1\n"); 
 
some code is here
 
fprintf(logfile,"successfully reached at debug-point 2"); 
 
Here segmantaion fault occur due to some reason

Now in this condition only debug-point1 will be print on logfile debug-point 2 print was written to buffer to be used for I/O operations with the specified stream logfile.  but its not flushed because it didnt get \n  and not written on logfile and program crash  so we thinks that crash occur after debug-point1

To overcome form this situation we can disable buffering for that logfile stream using setvbf with _IONBF : No buffering option.

setvbuf:

int setvbuf ( FILE * stream, char * buffer, int mode, size_t size );

 Stream :

Pointer to a FILE object that identifies an open stream.

buffer

User allocated buffer. Must be at least size bytes long.
If set to NULL, the function automatically allocates a buffer of the specified size.

 mode

Specifies a mode for file buffering:

_IOFBF : full buffering 

On output, data is written once the buffer is full. On Input the buffer is filled when an input operation is requested and the buffer is empty.

_IOLBF : Line buffering 

On output, data is written when a newline character is inserted into the stream or when the buffer is full, whatever happens first. On Input, the buffer is filled up to the next newline character when an input operation is requested and the buffer is empty.

_IONBF : No buffering 

No buffer is used. Each I/O operation is written as soon as possible. In this case, the buffer and size parameters are ignored.

size

Buffer size in bytes.
If the buffer argument is NULL, this determines the minimum size automatically allocated by the function for the buffer, otherwise it must be a value equal or lower to the size in bytes of the array specified as buffer.

Usualy people use this for changing the buffering option for Logfile.

By default all File stream are Line buffered. where stdout is also line buffered and stderr is not buffered

 

JIGAR PATEL

hey I am an Artist who love to write code…! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here JigAr Patel

More PostsWebsiteTwitterFacebook

You may like to read this also....

Post comment

*

CommentLuv badge
Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

latest comments

Find us on Facebook

Top Authors

35 posts
saurabh
22 posts
10 posts

Find us on stackoverflow

Polls

Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link