The reason for the garbage is that you never initialized temp
to an empty string at the beginning of main()
. You call init(temp)
after processing each command.
There are lots of other problems in your code:
orderedIds[i] = malloc(MAXCMD * sizeof(char*));
Since orderedIds[i]
is an array of char, not char*, you should multiply the size by sizeof(char)
. Also, it's not clear why you're using MAXCMD
as the size -- on the previous line this was the maximum number of words on a line, not the number of characters in a word.
strcpy(orderedIds[k], tok);
You should use strncpy()
to ensure that you don't copy more than the size of orderedIds[k]
.
Another option would be not to preallocate all the orderedIds[i]
in the first place. Instead of using strcpy()
, use strdup()
and assign this to orderedIds[k]
; if you do this, you have to remember to free()
all these strings.
A third option is not to copy the strings at all. Just assign the pointers returned by strtok()
to orderedIds[k]
. But in this case you mustn't call init(tmp)
until after you've forked.
strncpy(outputFile, orderedIds[numFile], strlen(orderedIds[numFile]));
The limit should be the size of outputFile
, not the length of orderedIds[numFile]
. strncpy()
will never copy more than the length of the source, you need to tell it the maximum size of the destination to prevent a buffer overflow.
outputfd = open(outputFile, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU | S_IRGRP | S_IROTH);
if (outputfd < 0) {
exit(EXIT_FAILURE);
}
You should call perror()
to report the reason that open()
failed.
puts(strerror(errno));
Call perror()
, like you do elsewhere.