Solved

Write to file inside thread!

Posted on 2003-10-30
11
390 Views
Last Modified: 2010-04-01
Hi i have problem with writing data in file.

Actualy I'm trying to make a log file.

But when I wish to write data inside thread function nothing is writen in to it.
If i write before or after thread evrything's work normaly.

I have defined my fstream variable as a static variable.

I'm using VC++ 6.0 on win NT/2000

thanks in advance

0
Comment
Question by:igora
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9648870
Can you show the code?

You need to use multithreaded runtime libraries.
0
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9648889
There can be it a problem of file handle inheriting?
Where and how do you open the stream?
How do you create the thread?
0
 

Author Comment

by:igora
ID: 9648982
//log.h

#ifndef LOG_H
#define LOG_H
#include <fstream.h>


class Log{

public:

      Log() {filus = new fstream;}
      ~Log() {delete [] filus;}
      BOOL Write(CString string);
      BOOL Open(char* filename);
      BOOL Close();
private:
      fstream* filus;
};

#endif


//log.cpp

#include "stdafx.h"
#include "log.h"



BOOL Log::Open(char* filename){
      
      filus->open(filename,ios::in | ios::out|ios::ate,filebuf::sh_write || filebuf::sh_read);
      if(filus->is_open()==0)
            return FALSE;
      else
            return TRUE;

}

BOOL Log::Write(CString string){

      if(filus->is_open()==0)
            return FALSE;
      filus->write(string,string.GetLength());

return TRUE;
}

BOOL Log::Close(){
      
      filus->close();
      if(filus->is_open()==0)
            return TRUE;
      else
            return FALSE;

}



///and aplication code

....
//call for function
            pThread = AfxBeginThread(MyFunction,(LPVOID)p);

....


UINT MyFunction (LPVOID obj)
{

      
      // TODO: Add your implementation code here
                MyClass::logFile->Open(LOG_FILE);
      MyClass::logFile->Write("Something\n");

//...the rest of code

}

i'm using multithreaded runtime libraries

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:igora
ID: 9648997
yes i also calll
MyClass::logFile->Close()

where logFile is

Log* logFile = new Log();
0
 
LVL 6

Accepted Solution

by:
GloomyFriar earned 50 total points
ID: 9649021
From my point of view it'll be better to do it as following:

BOOL Log::Write(char* filename, CString string){
  if (Open(filename))
  {
    filus->write(string,string.GetLength());
    return TRUE;
  }
  else
  {
    return FALSE;
  }
}
0
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9649025
BOOL Log::Write(char* filename, CString string){
 if (Open(filename))
 {
   filus->write(string,string.GetLength());
   Close();
   return TRUE;
 }
 else
 {
   return FALSE;
 }
}
0
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9649040
I mean Open-Write-Close. It'll be more reliable. Though and it is a little slower.
0
 

Author Comment

by:igora
ID: 9649089
great it work
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 9649104
Here's some supposedly thread-safe logging C code which I used for a Windoze project:

log.c:
--------8<--------
#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include "log.h"
#define      ROOT      "c:/Program files/My company name/My application name"

#define      MAXSIZE      (2L*1024L*1024L)      /* 2M */

static char logfile[] = ROOT"/log.txt";
static char bakfile[] = ROOT"/log_bak.txt";
static FILE *fout = NULL;
static CRITICAL_SECTION lock;
static BOOL lock_initialised = FALSE,lock_deleted = FALSE;

static void ReleaseLock(void);

/******** log_printf ******************************************************/
/*
 * Print stuff into the log file
 */
int log_printf(const char* fmt,...)
{
int retval;
char buf[5000];
va_list argptr;
size_t len;
long proposedsize;
time_t t;

/* Critical section must be initialised */

      if (!lock_initialised) {
            InitializeCriticalSection(&lock);
            lock_initialised = TRUE;
            atexit(ReleaseLock);
      }
      else if (lock_deleted)
            return 0;

/* Now we enter the critical section */

      EnterCriticalSection(&lock);

      time(&t);strncpy(buf,ctime(&t),sizeof(buf));
      buf[24] = ':';buf[25] = ' ';

/* Put the formatted string into buf */

      va_start(argptr,fmt);
      retval = _vsnprintf(&buf[26],sizeof(buf)-26,fmt,argptr);
      va_end(argptr);
      strncat(buf,"\n",sizeof(buf));
      buf[sizeof(buf)-1] = '\0';

/* Get the string length */

      len = strlen(buf);

/* Ensure that the log file is open */

      if (fout == NULL) {
            if ((fout = fopen(logfile,"a")) == NULL) {
                  LeaveCriticalSection(&lock);
                  return 0;
            }
      }

/* Get the file's size */

      fseek(fout,0L,SEEK_END);
      proposedsize = ftell(fout)+len;

/* Would this exceed the maximum allowed file size? */


      if (proposedsize > MAXSIZE) {

            fclose(fout);fout = NULL;

/* Delete backup file if it exists */

            unlink(bakfile);

/* rename existing to backup */

            if (rename(logfile,bakfile)) {
                  LeaveCriticalSection(&lock);
                  return 0;
            }

            if ((fout = fopen(logfile,"w")) == NULL) {
                  LeaveCriticalSection(&lock);
                  return 0;
            }
      }

/* Put string into file */

      fputs(buf,fout);

      fclose(fout);fout = NULL;

/* Return the number of arguments scanned */

      LeaveCriticalSection(&lock);
      return retval;
}

/******** ReleaseLock *****************************************************/
/*
 * Release critical section lock
 */
static void ReleaseLock(void)
{
      lock_deleted = TRUE;
      DeleteCriticalSection(&lock);
}
--------8<--------

log.h:
--------8<--------
#ifdef __cplusplus
extern "C"
#endif
      __declspec(dllexport) int log_printf(const char* fmt,...);

#define      LOG log_printf
--------8<--------


0
 
LVL 6

Expert Comment

by:GloomyFriar
ID: 9649106
Now about your question.
Whether arise by a call Write() any errors. If arise, what?
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 9649153
>   filebuf::sh_write || filebuf::sh_read

looks wrong to me. It should be

     filebuf::sh_write | filebuf::sh_read

Then, worker thread and main thread shouldn't use same file handle. Better, create an own Log instance using the same filename. Finally, you have to use a CriticalSection member in MyClass to make your Write function thread-safe,

Regards, Alex
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

687 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question