Can't get file size with fstat() or lseek() using file descriptor : <p>Trying to <code>open()</code> a file and then get size with <code>lseek()</code> or <code>fstat()</code> but both are resulting in a size of <code>0</code></p>

<p>For example, my line: </p>

<blockquote>
  <p>printf("lseek size : %d\nfstat size : %d\nfile desc: %d\n", fileSize,
  mystat.st_size, fd);</p>
</blockquote>

<p>using a file <strong>data1</strong> with contents:</p>

<pre><code>Jacobs-MBP:Desktop Kubie$ cat data1
2.3
3.1
5.3
1.1
</code></pre>

<p>prints:</p>

<pre><code>Jacobs-MBP:Desktop Kubie$ ./a.out 4 data1
byte size: 4
Opened: data1
lseek size : 0
fstat size : 0
file desc: 3
</code></pre>

<p>Below is my program, intent is to <code>mmap()</code> file into memory for other purposes.</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/stat.h&gt;
#include &lt;unistd.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;sys/mman.h&gt;
#include &lt;time.h&gt;

int main(int argc, char * argv[]) {

        int fd;
        struct stat mystat;
        void * pmap;
        int fileSize;

        if (argc &lt; 3) { printf("wrong # args\n"); return 0; }
        if (argc &gt; 3) { printf("wrong # args\n"); return 0; }

        sscanf(argv[1], "%d", &amp;byteSize);

        printf("byte size: %d\n", byteSize);

        fd = open(argv[2], O_RDWR | O_TRUNC);
        if (fd == -1) {
                perror("Error opening file!");
                exit(EXIT_FAILURE);
        } else {
                printf("Opened: %s\n", argv[2]);
        }

        if (fstat(fd, &amp;mystat) &lt; 0)  {
                perror("fstat error!");
                close(fd);
                exit(1);
        }

        lseek(fd, 0, SEEK_END);
        fileSize = lseek(fd, 0, SEEK_CUR);

        printf("lseek size : %d\nfstat size : %d\nfile desc: %d\n", fileSize, mystat.st_size, fd);

        pmap = mmap(0, fileSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (pmap == MAP_FAILED) {
                perror("mmap error!");
                close(fd);
                exit(1);
        }

        return 0;

}
</code></pre>

<p>I also noticed that the contents of <code>data1</code> file are erased on completion of this program.</p>

<p>Really a newbie with C so any help would be GREATLY appreciated.</p>
