I am learning, on how to create holes in files using lseek.
This is the code that I have written thus far...
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
int main()
{
int fd;
char name[20] = "Harry Potter";
// Creating a file
if( (fd = open( "book.txt", O_RDWR | O_CREAT , S_IWRITE | S_IREAD ) < 0 )) {
printf("\ncreat error");
}
// Seeking 100th byte, from the begining of the file
if ( lseek(fd, 100, SEEK_SET) == -1 ) {
if (errno != 0) {
perror("lseek");
}
}
// Writing to the 100th byte, thereby creating a hole
if( write(fd, name, sizeof(char)*strlen(name)) != sizeof(char)*strlen(name) ) {
if (errno != 0) {
perror("write");
}
}
// closing the file
if ( close(fd) == -1 ) {
if (errno != 0)
perror("close");
}
return 0;
}
and when I compile and execute this code I get an lseek error and also the name 'Harry Potter' is not being inserted into the file. This is the output when I execute the above code :
lseek: Illegal seek
Harry Potter
I am even trying to catch all errors. Kindly help me further.