Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Write to file inside thread!

Posted on 2003-10-30
11
Medium Priority
?
398 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

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

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Question has a verified solution.

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

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
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.

610 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