?
Solved

another question for fstream Vs fd (file descriptor)

Posted on 2003-02-25
7
Medium Priority
?
463 Views
Last Modified: 2008-02-01
Hi All

I had a Class which opened and locked the files. We were using fstream object. Now I am shifting basic C calls, open/write, using file descriptor.

Following is the code for original class as well as new class. Issue : New class is not working. And I am not able to find the error.


//////....Original Flock.cpp ***************

#include <stdio.h>

#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <iostream>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <iostream>
#include <fstream>

#define FILE_READ_LOCK                        (ios::in  |
IOS_NOCREATE)
#define FILE_READ_CREATE_LOCK            (ios::in)
#define FILE_WRITE_LOCK                        (ios::out | ios::trunc |
IOS_NOCREATE)
#define FILE_READWRITE_LOCK                  (ios::in  | ios::out   |
ios::trunc | IOS_NOCREATE)
#define FILE_WRITE_CREATE_LOCK             (ios::out | ios::trunc)
#define FILE_READWRITE_CREATE_LOCK      (ios::in  | ios::out   |
ios::trunc)
#define FILE_WRITE_EXCL_LOCK             (ios::out | ios::trunc |
IOS_NOREPLACE)
#define FILE_READWRITE_EXCL_LOCK      (ios::out | ios::trunc |
IOS_NOREPLACE)

class FLock
{
public:
      FLock( const char *fileName = 0, int op = 0);
      bool OpenAndLockFile( const char *fileName, int op);
      bool CloseAndUnLockFile( void );
      bool WriteLockFile( void );
      bool LockFile(  );
      bool UnLockFile( void );
      void CloseFile( void );
      char ReadCharacter( void );
      bool ReadLine( char * aline, int dwsize );
      bool WriteLine( char * aline, int dwsize );
      long ReadBlk( char * buf, long bufsize );
      long WriteBlk( char * buf, long bufsize );
      int GetFileDescriptor(void);
      inline fstream& GetIoStream() { return iostrm; }
private:
      fstream iostrm;
};

FLock::FLock( const char *fileName, int op )
{
        OpenAndLockFile(fileName, op); // calls clearinfo
}

bool FLock::OpenAndLockFile( const char *fileName, int op)
{
        errno = 0;

        iostrm.open(fileName, op | ios::out); //lockf doesnt permit for locks on files opened in read mode.

        if (!iostrm)
            {
                   cout<<"OpenAndLockFile - Cannot open file "<<fileName<<endl;
                  return false;
            }
        else
            {
            switch (op)
                  {
                case FILE_READ_LOCK:                // in
                case FILE_READ_CREATE_LOCK:         // in
                case FILE_READWRITE_LOCK:           // in, out, trunc
                case FILE_WRITE_EXCL_LOCK:          // out, trunc,
noreplace
                case FILE_WRITE_LOCK:               // out, trunc,
nocreate
                case FILE_WRITE_CREATE_LOCK:        // out, trunc
                case FILE_READWRITE_CREATE_LOCK:    // in, out, trunc
                    if (LockFile() == false) {
                        fprintf(stderr, "lock failed, %s\n", strerror( errno ) );
                        CloseFile();
                    }
                    else
                        return true;
                    break;

                default:
                    break;
                  }
            }

      return false;
}

bool FLock::CloseAndUnLockFile( void )
{
      if (!UnLockFile())
            return false;

      CloseFile();

      return true;
}

bool FLock::LockFile( void )
{
      int fd = GetFileDescriptor();
      return !lockf(fd, F_LOCK, 0);
}

bool FLock::UnLockFile( void )
{
      int fd = GetFileDescriptor();

      return !lockf(fd, F_ULOCK, 0);
}

void FLock::CloseFile( void )
{
      filebuf *b = iostrm.rdbuf();
      if (b && b->is_open())
            iostrm.close();
}

char FLock::ReadCharacter( void )
{
      char c;
      if (!iostrm)
            return EOF;

      iostrm.get(c);
      return c;
}

bool FLock::ReadLine(char * aline, DWORD dwsize)
{
      if (!iostrm)
            return false;

      iostrm.getline(aline, dwsize, '\n');
      return (!iostrm == false);
}

bool FLock::WriteLine( char * aline, DWORD dwsize)
{
      if (!iostrm)
            return false;

      iostrm.write(aline, dwsize);
      return (!iostrm == false);
}

long FLock::ReadBlk( char * buf, long bufsize)
{
      iostrm.read(buf, bufsize);
      if (!iostrm.bad())
            return iostrm.gcount();
      else
            return 0;
}

long FLock::WriteBlk( char * buf, long bufsize)
{
      iostrm.write(buf, bufsize);
      if (!iostrm.bad())
            return bufsize;
      else
            return 0;
}

int FLock::GetFileDescriptor()
{
      filebuf *b = iostrm.rdbuf();
      return b ? b->fd() : -1;
}

#############...........................................................
..

AND the changed file is


#############...............Modified
Flock.cpp............................

#include <stdio.h>

#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <iostream>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <iostream>
#include <fstream>

#define FILE_READ_LOCK              O_RDONLY
#define FILE_READ_CREATE_LOCK       O_RDONLY | O_CREAT
#define FILE_WRITE_LOCK             O_WRONLY | O_TRUNC
#define FILE_READWRITE_LOCK         O_RDWR | O_TRUNC
#define FILE_WRITE_CREATE_LOCK      O_WRONLY | O_CREAT | O_TRUNC
#define FILE_READWRITE_CREATE_LOCK  O_RDWR | O_CREAT | O_TRUNC
#define FILE_WRITE_EXCL_LOCK        O_WRONLY | O_TRUNC | O_CREAT |
O_EXCL
#define FILE_READWRITE_EXCL_LOCK    O_WRONLY | |O_TRUNC | O_CREAT |
O_EXCL

class FLock
{
public:
      FLock( const char *fileName = 0, int op = 0);
      bool OpenAndLockFile( const char *fileName, int op);
      bool CloseAndUnLockFile( void );
      bool WriteLockFile( void );
      bool LockFile(  );
      bool UnLockFile( void );
      void CloseFile( void );
      char ReadCharacter( void );
      bool ReadLine( char * aline, int dwsize );
      bool WriteLine( char * aline, int dwsize );
      long ReadBlk( char * buf, long bufsize );
      long WriteBlk( char * buf, long bufsize );
      int GetFileDescriptor(void);
      ssize_t readline(int, void *, size_t);
private:
      int m_fhFLock;
};

FLock::FLock( const char *fileName, int op )
{
        OpenAndLockFile(fileName, op); // calls clearinfo
}

bool FLock::OpenAndLockFile( const char *fileName, int op)
{
        errno = 0;

        m_fhFLock=open(fileName, op|O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);//lockf doesnt permit for locks on files opened in read mode.

       if (m_fhFLock==-1)
            {
                   cout<<"OpenAndLockFile - Cannot open file "<<fileName<<endl;
                  return false;
            }
        else
            {
            switch (op)
                  {
                case FILE_READ_LOCK:                // in
                case FILE_READ_CREATE_LOCK:         // in
                case FILE_READWRITE_LOCK:           // in, out, trunc
                case FILE_WRITE_EXCL_LOCK:          // out, trunc,
noreplace
                case FILE_WRITE_LOCK:               // out, trunc,
nocreate
                case FILE_WRITE_CREATE_LOCK:        // out, trunc
                case FILE_READWRITE_CREATE_LOCK:    // in, out, trunc
                    if (LockFile() == false) {
                        fprintf(stderr, "lock failed, %s\n", strerror( errno ) );
                        CloseFile();
                    }
                    else
                        return true;
                    break;

                default:
                    break;
                  }
            }

      return false;
}

bool FLock::CloseAndUnLockFile( void )
{
      if (!UnLockFile())
            return false;

      CloseFile();

      return true;
}

bool FLock::LockFile( void )
{
      int fd = GetFileDescriptor();
      return !lockf(fd, F_LOCK, 0);
}

bool FLock::UnLockFile( void )
{
      int fd = GetFileDescriptor();

      return !lockf(fd, F_ULOCK, 0);
}

void FLock::CloseFile( void )
{
      if (m_fhFLock !=-1)
            close(m_fhFLock);

}

char FLock::ReadCharacter( void )
{
      char c;
      if (m_fhFLock==-1)
            return EOF;

      read(m_fhFLock,&c,1);
      return c;
}

bool FLock::ReadLine(char * aline, DWORD dwsize)
{
      if (m_fhFLock==-1)
            return false;

      ssize_t status=readline(m_fhFLock,aline,dwsize);

      if (status == -1)
            return false;
      else
            return true;
}

bool FLock::WriteLine( char * aline, DWORD dwsize)
{
      if (m_fhFLock==-1)
            return false;

      ssize_t status=write(m_fhFLock,aline,dwsize);

      if (status == -1)
            return false;
      else
            return true;
}

long FLock::ReadBlk( char * buf, long bufsize)
{
      ssize_t status=read(m_fhFLock, buf, bufsize);
      if (status != -1)
            return status;
      else
            return 0;
}

long FLock::WriteBlk( char * buf, long bufsize)
{
      ssize_t status=write(m_fhFLock,buf,bufsize);
      if (status!=-1)
            return bufsize;
      else
            return 0;
}

int FLock::GetFileDescriptor()
{

    if (m_fhFLock < 0)
        return -1;
    else
        return m_fhFLock;
}

ssize_t FileLock::readline(int fd, void *vptr, size_t maxlen)
{
    int     n, rc;
    char    c, *ptr;

    ptr = (char *)vptr;
    for (n = 1; n < maxlen; n++) {
            again:
            if ( (rc = read(fd, &c, 1)) == 1) {
                  *ptr++ = c;
                  if (c == '\n')
                        break;      /* newline is stored, like
fgets() */
            } else if (rc == 0) {
                  if (n == 1)
                        return -1;      /* EOF, no data read */
                  else
                        break;            /* EOF, some data was
read */
            } else
            {
                  if (errno == EINTR)
                        goto again;
                  return(-1);            /* error, errno set by
read() */
            }
      }

      *ptr = '\0';      /* null terminate like fgets() */
      return(n);

}


#############...........................................................
.



Can somebody please tell me -- WHERE AM I WORNG.. :((((

-Ajay

0
Comment
Question by:avi_india
[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
7 Comments
 
LVL 4

Expert Comment

by:abancroft
ID: 8019751
*How* isn't it working? Does it fail to compile? Is there a runtime bug that fails a specific test case?
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 8021815
If the first one works and the second one does not work, then there is a fair-to-middlin' chance that the problem is related to some differences that exist between the two versions.

-- Dan
0
 

Author Comment

by:avi_india
ID: 8022931
that is the difference I am trying to figure out.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 49

Expert Comment

by:DanRollins
ID: 8024001
Me two.  Why don't you compare the two and see what is different about the second?  Just an idea.... I hope it works.
-- Dan
0
 

Author Comment

by:avi_india
ID: 8026795
Found the reason..

If it is not contempt... anybody (who has good knowledge of c++, especially fstream class), would have found it... Alas.. i didn'y have tilee somewhile ago.

fstream::getline (called in ReadLine of FLock), doesn't store new line (or what ever the delinmiter may be) character in its output.
While Flock:readline was storing it in the output buffer.
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 8026903
I knew you could do it!
Since you found the answer to this yourself, you should post to Community Support and request a refund.  That will close the question.  Post here and be sure to paste in the URL of this question (QID=Q_20529232):  
   http://www.experts-exchange.com/Community_Support/qAskQuestion.jsp

-- Dan
0
 
LVL 1

Accepted Solution

by:
Computer101 earned 0 total points
ID: 8029233
Points refunded and placed in PAQ

Computer101
E-E Admin
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
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…
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 learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

752 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