Purpose:
Understand how tomanipulatefiles by using system calls ofopen(), stat(),lseek(), write(), and create().
Instruction:
Write a C program (double
copy) that allows a user to extract some part of an existing file (
fileSource)
and copy it twice to a new file
fileTarget
. The user can specify (1) the number of bytes (num1)as an offsetfrom the beginning of
filesource, (2)
how many bytes (num2) that will be extracted from it, and ,(3) the new
fileTarget
name.
>doublecopy
num1num2filesourcefileTarget
For instance, if the executable name isdouble
copy,extract500bytes fromdata.datstarting from the beginning of the file, move 100 bytes and append again.
>doublecopy0 500 data.dattarget.dat
For instance, if the executable name isdoublecopy,extract300bytes fromdata.datstarting at 50 bytes from the beginning of the file to target.dat, move 100 bytes and append it again:
>doublecopy50 300 data.dattarget.dat
Note:
- You need to usethe command line argumentto acquire thenum1,num2, andfiletargetname. ( 5pts)
- You need to useopen()system call to open an existing file. Print out the error message if the
filesource
does not existby usingperror() function. (5pts)
- You need to check if thesize of
filesource
againstthe values ofnum1andnum2.Print out the warningmessage if the file size is smaller thannum1+num2. In this case, your program will just copy the content up to the end of the source file.This is the situation that the file size is too small to copy the requested size of the content. (10pts)
- Once the
filesource
is open, uselseek() system call to move thefile pointerto the proper location for starting reading:num1from the beginning of thefilesourcefile. ( 10pts)
- Create a new file
fileTarget
and use read() and write() system call to copy the content from
filesource
to
fileTarget
fornum2bytes. Close files when the extraction process is complete. You should test your program for the cases when num!+num2 > file size; num1+num2 < file="" size="" and="" num1=""> filesize(10pts)
The thing to Submit:
- A c source codedouble
copy.cwithheader, error checking including the max size of file content you can copy, and documentation as comments in the program. Ifnum1+num2 is greater than the size offilesource, your program may only copy up to the end of the file.
- Testing resultswith screenshotsto prove a working copy of the executable according to the instruction. You testing cases should include file size that can handlenum1+num2and cannot handlenum1+num2.
Thesystemcall manual can also be accessed from the following links otherthaneve machine:
- http://codewiki.wikidot.com/c:system-calls:write (with examples)
- http://linux.die.net/man/2/lseek
- http://man7.org/linux/man-pages/man2/open.2.html
Note: Use stat() function to retrieve a filesize is:
#include struct stat st; stat(filename, &st); size = st.st_size;