views:

78

answers:

3

I am writing the log file in my c application, the method for writing the file is

fopen_s(&fMainFile, "c:\\LOG\\Filter.txt", "a");
fprintf(fMainFile, "SomeText");
fclose(fMainFile);

I open the handle, after writing I closed it, but this writing crash my application after a while, can any one sort out this problem, that how much dangerous to open and close the handle again and again, or proposed any other approach for writhing the file.

+1  A: 

How is fMainFile defined? I suspect that you shoud have:

fopen_s(&fMainFile, "c:\\LOG\\Filter.txt", "a");
fprintf(&fMainFile, "SomeText");
fclose(&fMainFile);

Pass a reference to the fprintf/fclose functions as you did with fopen_s!

EDIT: this answer is not valid, since fopen_s takes a FILE** parameter as stated below in comments.

EDIT2: As i said in comments you should do buffered writing (either with your own buffer or using setvbuf() functions for your file). Also, do not reopen/close the file every time, but leave it open and close it only when you really need to (input is finished). use fflush() to force writing to disk (instead of fclose()).

PeterK
FILE *fMainFile; I defined it global.
Arman
It seems like `fopen_s` takes `FILE**` while `fclose` takes `FILE*` http://msdn.microsoft.com/en-us/library/z5hh6ee9(VS.80).aspx
Steve
I see, didn't expect that. Discard this answer then, the error must be somewhere else. Maybe if you post more of your code we will be able to find it.
PeterK
@Peterk, I have a application which receive data from network and write in the log file. The rate of Data input is almost 100 Packet/5 sec and the size of each packet is maximum 400 bytes.
Arman
Then i would suggest buffering the input and writing in larger chunks, say about 16kB. Also, why do you close the file everytime? Leave it opened and close it when all writing is finished. You can use fflush() to force a write to disk.
PeterK
+1  A: 

You should definitely add some error-checking to your code, see http://msdn.microsoft.com/en-us/library/z5hh6ee9%28VS.80%29.aspx for a specific fopen_s example. Maybe you can get some more information that way. Apart from that, your code snippet looks correct.

Greg S
A: 

You must check the return value of fopen_s and only call fprintf and fclose if it is successful

if (fopen_s(&fMainFile, "c:\\LOG\\Filter.txt", "a") == 0)
{
  fprintf(fMainFile, "SomeText");
  fclose(fMainFile);
}
David Sykes