Rectangle 27 0

unistd.h C copy file contents from EOF to SOF?


From some of your comments it looks like you want to reverse the order of the lines in a text file. Unfortunately you're not going to get that with such a simple program. There are several approaches you can take, depending on how complicated you want to get, how big the files are, how much memory is on hand, how fast you want it to be, etc.

Here are some different ideas off the top of my head:

There may be more elaborate/clever tricks, but those are the more obvious, straightforward approaches.

Note
Rectangle 27 0

unistd.h C copy file contents from EOF to SOF?


// define an offset that exceeds the maximum line length
int offset = 256;
char buffer[256];
// determine the file size
off_t size = lseek( src, 0, SEEK_END );
off_t pos = size;
// read block of offset bytes from the end
while( pos > 0 ) {
    pos -= offset;
    if( pos < 0 ) {
        //pos must not be negative ...
        offset += pos;   // in fact decrements offset!!
        pos = 0;
    }
    lseek( src, pos, SEEK_SET );
    // add error checking here!!
    read(src, buffer, offset );
    // we expect the last byte read to be a newline but we are interested in the one BEFORE that
    char *p = memchr( buffer, '\n', offset-1 );
    p++;  // the beginning of the last line
    int len = offset - (p-buffer);  // and its length
    write( dst, p, len );
    pos -= len;            // repeat with offset bytes before the last line
}
loc = lseek(src, offset, SEEK_END);
loc+offset
lseek()
offset
while( loc > 0 )
{
    // Read bytes
    block = read(src, buffer, 5);

    // Write to output file
    write(dst, buffer, block);

    // Move the pointer again five bytes before the last offset
    loc = lseek(src, loc+offset, SEEK_SET);
}

Btw. is there a blank between "Line" and "3"? if so offset has to be -6 because of the newline

I'm still having the same problem only now I get eLine3

If the line length is variable, you could do something like the following instead:

If you take a look at how I changed my method this works. However the output is: 3eniL2eniL1eniL all in same line with no spacing between words.

lseek() doesn't change or return the file size. What it returns is the position where the 'cursor' is set to. So when you call

twice it will always set the cursor to the same position again. I guess you want to do something like this:

Note