C: lseek() related question.

Posted by Andrei Ciobanu on Stack Overflow See other posts from Stack Overflow or by Andrei Ciobanu
Published on 2010-04-04T08:57:08Z Indexed on 2010/04/04 9:03 UTC
Read the original article Hit count: 435

Filed under:
|
|

I want to write some bogus text in a file ("helloworld" text in a file called helloworld), but not starting from the beginning. I was thinking to lseek() function.

If I use the following code:

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

#define fname "helloworld"
#define buf_size 16

int main(){

    char buffer[buf_size];
    int fildes,
        nbytes;
    off_t ret;

    fildes = open(fname, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
    if(fildes < 0){
        printf("\nCannot create file + trunc file.\n");
    }
//modify offset
    if((ret = lseek(fildes, (off_t) 10, SEEK_END)) < (off_t) 0){
        fprintf(stdout, "\nCannot modify offset.\n");
    }
    printf("ret = %d\n", (int)ret);

    if(write(fildes, fname, buf_size) < 0){
        fprintf(stdout, "\nWrite failed.\n");
    }

    close(fildes);

    return (0);
}

, it compiles well and it runs without any apparent errors. Still if i :

cat helloworld

The output is not what I expected, but:

helloworld
Can

Where is "Can" comming from, and where are my empty spaces ?

Should i expect for "zeros" instead of spaces ? If i try to open helloworld with gedit, an error occurs, complaining that the file character encoding is unknown.

© Stack Overflow or respective owner

Related posts about posix

Related posts about c