Computing.Net > Forums > Programming > Writing to a file in C

Computing.Net: Over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to sign up now, it's free!

Writing to a file in C

Reply to Message Icon

Original Message
Name: rerock
Date: May 20, 2004 at 06:42:32 Pacific
Subject: Writing to a file in C
OS: Windows 2000
CPU/Ram: 256 MB
Comment:

Ok here is the deal:
subject: Writing data to a file in C
problem: I need to be able to write the data as the program is running not just when I close the file.
example: Im running a packet sniffer program that constantly writes packet data to an output(standard right now... need it to be in a file)
the program runs fine when it closes on its own but when it stops suddenly none of the data is written to a file.

Help would be greatly appreciated currently I am useing this method

*fpointer = fopen(file_name,"wb");

/*in a loop */
fprintf(fpointer,"Time: %s Average:%f\n",timestr,average);

fclose(fpointer); /* it only whites to the file when this is called*/

A successful man doesnt know much. He surrounds humself with people who do.



Report Offensive Message For Removal


Response Number 1
Name: Don Arnett
Date: May 20, 2004 at 07:36:43 Pacific
Reply: (edit)

When you write to a file, many times the data is actually written to a buffer and periodically the buffer is written to the file. The purpose of this is to save I/O time by writing only when the buffer gets full. Most likely, what is happening is that when your program does not stop cleanly and thus does not execute the fclose, the buffer is not getting written.

For a program like yours, you want to cause it to write the data every time, whether the buffer is full or not, because it's important to get the data into the file.

To do this, add an 'fflush()' command after your fprintf().

fprintf(fpointer,.......);
fflush(fpointer);


Note that you can use fflush on stdin and stdout also.

fflush(stdout) causes output to go immediately to stdout, rather than waiting for full buffers. I've had to do this before, but don't remember the situation that made it necessary.

fflush(stdin) flushes input buffers, so you can be sure that there are no unread characters when you prompt for new input.


Report Offensive Follow Up For Removal







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home








Do you have your own blog?

Yes
No
I did before
I will soon


View Results

Poll Finishes In 4 Days.
Discuss in The Lounge
Poll History




Data Recovery Software