/*
 * Copyright ©2026 Soham Pardeshi. All rights reserved.
 * Permission is hereby granted to students registered for University of
 * Washington CSE 333 for use solely during Summer Quarter 2026 for
 * purposes of the course. No other use, copying, distribution, or
 * modification is permitted without prior written consent. Copyrights
 * for third-party components of this work must be honored. Instructors
 * interested in reusing these course materials should contact the author.
 */

#ifndef FILE_DESCRIPTOR_H_
#define FILE_DESCRIPTOR_H_

#include <fcntl.h>
#include <unistd.h>

#include <iostream>

class FileDescriptor {
 public:
  explicit FileDescriptor(const char* file) {  // Constructor
    fd_ = open(file, O_RDONLY);
    // On error, we get fd_ = -1
    // error handling is in the Destructor
  }

  ~FileDescriptor() {  // Destructor
    // No need to close an invalid descriptor
    if (fd_ >= 0) {
      int res = close(fd_);
      if (res == -1) {
        std::cerr << "Error Closing File" << std::endl;
      }
    }
  }

  int get_fd() const { return fd_; }  // inline member function

 private:
  int fd_;  // data member
};  // class FileDescriptor

#endif  // FILE_DESCRIPTOR_H_