Solved

Write to file inside thread!

Posted on 2003-10-30
11
373 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
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
ScreenConnect 6.0 Free Trial

Want empowering updates? You're in the right place! Discover new features in ScreenConnect 6.0, based on partner feedback, to keep you business operating smoothly and optimally (the way it should be). Explore all of the extras and enhancements for yourself!

 

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

ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
TCP/IP Socket - connection close results in data lost 14 136
Exception thrown at 0x00007FFD5BC81F28 7 44
Dialogbox API leak? 18 96
Why isn't object file created? 6 59
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

803 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