Reputation: 135
Hey guys using POSIX API system calls read
, write
, open
, etc. I can open, read, write to a file and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?
I currently have:
filein = open(argv[1],O_RDONLY,0);
to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)
I tried :
j=0;
filein = open(argv[j],O_RDONLY,0);
but that prints out contents of argv0 into my outputfile.
I am stuck on the next stage to do more than one file. (I also have an EOF
loop so after 1 file it exits-How would I make this continue for the next file).
Please could you help me with how to approach the next stage? Thanks.
Upvotes: 1
Views: 288
Reputation: 31221
argv[0]
is the name of the program.
argv[1]
is the 1st command line parameter.
argv[2]
is the 2nd command line parameter.
etc.
So:
1
, instead of 0
(i.e., j=0
is incorrect).Think about the algorithm before writing the code.
Now you can write the code.
You might get bonus points if you include error handling. (What happens when the file is missing, is not readable, the file system is corrupt, or the machine has run out of memory or disk space?)
If you want to concatenate two file names to a third, you need to rethink the algorithm, and what you need. There is a difference between "read the first two files given on the command line and write them to the third file" and "append all the files given on the command line to the last file given."
The algorithm:
You will notice a lot of redundancy at this point.
This algorithm is a bit more challenging, but removes the redundancy.
For this you will need to understand argc
and its relationship with argv
. In pseudo-code:
if number_of_arguments < 2 then
print "This program concatenates files; two or more file names are required."
exit
end
int outfile = open arguments[ number_of_arguments ] for writing
int j = 1
while j < number_of_arguments do
int infile = open arguments[ j ] for reading
string contents = read infile
write contents to outfile
close infile
increment j
end
close outfile
If you are having trouble with C syntax, search for tutorials. For example:
Upvotes: 4
Reputation: 55882
Use a loop to read all the files. Start at 1 to skip the current executing process which is located at argv[0].
for(int i = 1; i < argc; ++i)
{
int filein = open(argv[i],O_RDONLY,0);
// ... process file
close(filein)
}
Upvotes: 2
Reputation: 4464
to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)
fopen(argv[2], ...)
Upvotes: 1
Reputation: 7466
argv[0] is the name of the program. argv[1] is the first then you pass on the command line.
Open your output file then each input file. read each input file into the output file then close them all and exit.
Upvotes: 1