title: What is the default mode for open() calls with O_CREAT and how to properly set it while opening/creating files
body: <p>I am trying to recreate the basic functionality of fopen() using the I/O system calls. I am somehow suppose to "set the default mode for open() calls with O_CREAT" however am unsure how to go about this. It's not perfect but this is what I've got so far. </p>
  
  <pre><code>MYFILE * myfopen(const char * path, const char * mode){
  MYFILE *fp = (MYFILE *)malloc(sizeof(MYFILE)); //EDITED
  int fd;
    switch(mode[0]){
              case 'r':
                      fd=open(path, O_RDONLY | O_CREAT, 0440);
                      break;
              case 'w':
                      fd=open(path, O_WRONLY | O_CREAT | O_TRUNC, 0220);
                      break;
              default:
                      fd=open(path, O_RDWR | O_CREAT | O_TRUNC, 0660);
    }
  
   if(fd &lt; 0){
       return NULL;
   }
  
   fp-&gt;fileD=fd;
   fp-&gt;offset=0;
   return fp;
  } 
  </code></pre>
  
  <p>fileD will be the file descriptor returned by the open call. I think the rest is self-explanatory. </p>
  
  <p>It compiles but I'm getting a "segmentation fault" error when I try to run it. This function also fails to open a new file and associate a file descriptor to it.</p>
  
  <p>I think the segmentation error might be somewhere in here:</p>
  
  <pre><code>int myfputc(int c, MYFILE * fp){
  
   if(write(fp-&gt;fileD, &amp;c, 1) == -1){
      return 1;
   }
   ++fp-&gt;offset; //how to gain access to the current offset of the stream?
   return 0;
  }
  </code></pre>
  
  <p>Where I'm trying to recreate fputc.</p>
  
  <p>Here is the MYFILE struct:</p>
  
  <pre><code>typedef struct {
      int fileD; // descriptor
      int bufferSz; // buffer size
      int bufferCh; // # of bytes in stream
      int offset; //current offset position
      int errorF; // error flag
      int EOFF; // EOF flag
  
  } MYFILE;
  </code></pre>