Solved

Write to file inside thread!

Posted on 2003-10-30
11
352 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
 

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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

706 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now