Search code examples
csendfile

A simple sendfile program, but not works


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

int main(){
    int fd1,fd2,rc;
    off_t offset = 0;
    struct stat stat_buf;

    fd1=open("./hello.txt",O_RDONLY); //read only
    fd2=open("../",O_RDWR);           //both read and write
    fstat(fd1, &stat_buf);            //get the size of hello.txt
    printf("file size: %d\n",(int)stat_buf.st_size);
    rc=sendfile (fd2, fd1, &offset, stat_buf.st_size);
}

So as you have seen, it's quite a simple program. But I just can't find hello.txt in ../ My aim is to see what happens if I put a whatever number, says 10, instead of st_size which may be hundreds of bytes.

Edit:

Thanks for your answers. Well, I followed your advice and changed

 fd2=open("../",O_RDWR);

to

 fd2=open("../hello.txt",O_RDWR);

Also, I checked the return value of fstat and sendfile, everything is ok.

But the problem is still the same.


Solution

  • 1>

      fd1=open("./hello.txt",O_RDONLY); //read only
      fd2=open("../",O_RDWR);           //both read and write
    

    replace with

     fd1=open("../hello.txt",O_RDONLY); //read only
      fd2=open("../your_file_name",O_RDWR);         
    

    2>

     fstat(fd1, &stat_buf); 
    

    will fill up some info related to fd1 file in stat_buf . Here size of that file is also return in that structure with st_size element.

    now in

     rc=sendfile (fd2, fd1, &offset, stat_buf.st_size);
    

    total stat_buf.st_size bytes are going to send on fd2 file. if here if you write 10 then only 10 bytes will go in fd2.