Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

another question for fstream Vs fd (file descriptor)

Posted on 2003-02-25
7
Medium Priority
?
470 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
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
Industry Leaders: 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!

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
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…
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 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.
Suggested Courses

564 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