Walt Mankowski on Mon, 17 Jun 2002 00:50:18 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] unix cp function call (thanks)


On Sun, Jun 16, 2002 at 04:24:13PM -0400, Fred K Ollinger wrote:
> > system(3) only takes one parameter -- a pointer to a character array.
> > What's the problem?
> 
> Both filenames are pointers to char arrays.
> 
> Plus, there was a really big thread on my system calls are bad C, or not C
> at all in my book. I shy away from system calls b/c I feel it's cheesy,
> but other pluggers listed many reasons why system is bad news.

I'm not arguing the pros and cons of using system, which have already
been discussed here.  But I just don't think the fact that both
filenames are char *'s is a reason not to use it.  You really need to
become comfortable working with char *'s if want to program
effectively in C.

Here's some sample code that does the cp using system where the two
filenames are char *'s.  Even if you decide not to use system to do
the copy, perhaps you'll be able to use it as an example elsewhere in
your program.

Also note that I'm not doing any error checking.  In the real world
you'd need to check the return values of malloc() and system() and
take appropriate action if they fail.

void copy_file(char *to, char *from) {
  char *cmd;

  /* add 5 extra bytes for "cp", two spaces, and a trailing null */
  cmd = malloc(strlen(to) + strlen(from) + 5);

  sprintf(cmd, "cp %s %s", to, from);
  system(cmd);

  free(cmd);
}

Walt

Attachment: pgpksMDEk1l4m.pgp
Description: PGP signature