Friday, October 17, 2008

Difference in ls and du output.

Hi all,

Recently I came across sparse file which may not be new to you. See following output.


vinitd@pe-lt271:~/prog$ ls -alh /tmp/file
-rw-r--r-- 1 vinitd vinitd 1.1G 2008-10-17 15:53 /tmp/file
vinitd@pe-lt271:~/prog$ du -sh /tmp/file
20K /tmp/file
vinitd@pe-lt271:~/prog$

This is achieved using following program.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


#define PATH "/tmp/file"
#define GB *1024*1024*1024
#define MB *1024*1024
int main()
{

        int fd;

        fd = open(PATH, O_RDWR);
        if(0 > fd) {
                perror("open");
                return -1;
        }
        if((-1 == lseek(fd, 1 GB, SEEK_SET))) {
                perror("lseek");
                return -1;
        }
        if (-1 == write(fd, "\0", 1)) {
                perror("write");
                return -1;
        }

        close(fd);

        return 0;
}


Here the filesystem space is efficiently used when file is mostly empty, but it gets converted into real block with zeros while reading such file. Hence file copy program may copy the entire file including zero blocks.

1 comment:

NINAD...ENGINEER CUM POET! LOL!! said...

hey, i am a fellow blogger..this post of yours was informative...

p.s...i have joined the blog& bloggers community on orkut..so came across your blog there