Featured post
posix - C: read in more than one file -
hey guys using posix api system calls read
, write
, open
, etc. can open, read, write file , copy contents output file. how go copying more 1 file output file using related system calls only?
i have:
filein = open(argv[1],o_rdonly,0);
to open 1 file.(which argv1 i'd know how argv2 , argv3 etc.)
i tried :
j=0; filein = open(argv[j],o_rdonly,0);
but prints out contents of argv0 outputfile.
i stuck on next stage more 1 file. (i have eof
loop after 1 file exits-how make continue next file).
please me how approach next stage? thanks.
background
argv[0]
name of program.
argv[1]
1st command line parameter.
argv[2]
2nd command line parameter.
etc.
so:
- start loop @
1
, instead of0
(i.e.,j=0
incorrect). - be sure close file after reading , before opening next file.
algorithm
think algorithm before writing code.
- set counter index of first argument.
- open file.
- assign handle open file.
- read file contents.
- write (if required) file contents.
- close file using handle.
- increment counter.
- loop until there no more command line arguments.
now can write code.
you might bonus points if include error handling. (what happens when file missing, not readable, file system corrupt, or machine has run out of memory or disk space?)
concatenating files
if want concatenate 2 file names third, need rethink algorithm, , need. there difference between "read first 2 files given on command line , write them third file" , "append files given on command line last file given."
read two, write one
the algorithm:
- make sure there 3 parameters.
- create file handle variable third file (output).
- create file handle variable first file (input).
- create file handle variable second file (input).
- open first file reading.
- open second file reading.
- open third file writing.
- read contents of first file , write them third file.
- read contents of second file , write them third file.
- close third file.
- close second file.
- close first file.
you notice lot of redundancy @ point.
read n, write one
this algorithm bit more challenging, removes redundancy.
- make sure there @ least 2 parameters.
- open last file writing.
- loop on every file name to, not including, last file name given:
- open input file reading.
- write contents of file last file.
- close input file.
- close output file.
for need understand argc
, relationship argv
. in pseudo-code:
if number_of_arguments < 2 print "this program concatenates files; 2 or more file names required." exit end int outfile = open arguments[ number_of_arguments ] writing int j = 1 while j < number_of_arguments int infile = open arguments[ j ] reading string contents = read infile write contents outfile close infile increment j end close outfile
tutorials
if having trouble c syntax, search tutorials. example:
- Get link
- X
- Other Apps
Comments
Post a Comment