title: Simple create - lseek - read program in C
body: <p>I'm trying to create a simple program which creates a file, writes on it, then moves back the pointer and finally reads it.</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(){ 
  
    int fd = creat("/home/alum/Class/ej",S_IRWXU);
    if(fd==-1){
      printf("Error %d\n",errno);
      return 1;
    }
  
    ssize_t size = write(fd, "Halo",4);
    if(size==-1){
      printf("Error %d\n",errno);
      return 1;
    }
  
    char string[50];
    lseek(fd,0,SEEK_SET);  
    while((size = read(fd, string, 49)) &gt;0){    
      printf("Read[%d]: %s\n",size,string);
    }
  
    printf("Size: %d\n",size);
  
    if(size==-1){
      printf("Error %d\n",errno);
      return 1;
    }
  
    int c=close(fd);
    if(c==-1){
      printf("Error %d\n",errno);
      return 1;
    }
  
    return 0;
  }
  </code></pre>
  
  <p>My problem is that "lseek" seems not to be working. I always get size "-1" when I try to read, so I assume I'm not going back to the beginning of the file... Any suggestions?</p>
  
  <p>I've seen some questions related to lseek but I haven't found a solution to my problem.</p>
  
  <p>EDIT:</p>
  
  <p>I changed</p>
  
  <pre><code>  int fd = creat("/home/alum/Class/ej",S_IRWXU);
  </code></pre>
  
  <p>to</p>
  
  <pre><code>  int fd = open("/home/alum/Class/ej",O_CREAT|O_RDONLY|O_WRONLY|O_TRUNC);
  </code></pre>
  
  <p>and also tried</p>
  
  <pre><code>  int fd = open("/home/alum/Class/ej",O_CREAT|O_RDONLY|O_WRONLY|O_TRUNC,0700);
  </code></pre>
  
  <p>As suggested but I keep getting the same error.</p>