?
Solved

Write to file inside thread!

Posted on 2003-10-30
11
Medium Priority
?
393 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
Independent Software Vendors: 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 200 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

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

777 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