My program is working almost as it should. The intended purpose is to read the file from the end and copy the contents to destination file. However what confuses me is the lseek()
method more so how I should be setting the offset.
My src
contents at the moment are:
Line 1
Line 2
Line 3
At the moment what I get in my destination file is:
Line 3
e 2
e 2...
From what I understand calling int loc = lseek(src, -10, SEEK_END);
will move the "cursor" in source file to then end then offset it from EOF to SOF for 10 bytes and the value of loc will be the size of file after I have deducted the offset. However after 7h of C I'm almost brain dead here.
int main(int argc, char* argv[])
{
// Open source & source file
int src = open(argv[1], O_RDONLY, 0777);
int dst = open(argv[2], O_CREAT|O_WRONLY, 0777);
// Check if either reported an erro
if(src == -1 || dst == -1)
{
perror("There was a problem with one of the files.");
}
// Set buffer & block size
char buffer[1];
int block;
// Set offset from EOF
int offset = -1;
// Set file pointer location to the end of file
int loc = lseek(src, offset, SEEK_END);
// Read from source from EOF to SOF
while( loc > 0 )
{
// Read bytes
block = read(src, buffer, 1);
// Write to output file
write(dst, buffer, block);
// Move the pointer again
loc = lseek(src, loc-1, SEEK_SET);
}
}