How to exec and system in C ?

Status
Not open for further replies.

yhboy

Newbie level 3
Joined
Mar 8, 2005
Messages
4
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,316
Hi
I would like to use exec or system to do a dos command:
copy <file1>+<file2>+<file3>.....<file N-1> <file N>

How to do that?
 

Re: exec and system in C

This should work fine:
Code:
#include <stdlib.h>
int main(void)
{
  system("copy file1+file2+file3 outfile");
  return 0;
}
I don't know about exec, there is no such thing in ANSI C.

Or were you asking how to generate a string with all those "file..." words in it?
 

Re: exec and system in C


Thanks
But I want the number fo file is adjustable, not limited in 3 files.
The file1, file2 ..and so on are the arguments of main function.
 

Re: exec and system in C

Code:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int n;
  char buf[1000], *p;

  /* This lacks checks for too-few arguments, or buffer-overflow */
  p = buf + sprintf(buf, "copy");
  for (n=1; n<argc; n++)
    p += sprintf(p, "%c%s", (n==1 || n==argc-1 ? ' ' : '+'), argv[n]);
  puts(buf);   /* Change "puts" to "system" in the final version */
  return 0;
}
I hope that wasn't your homework!
 

Re: exec and system in C


Thanks a lot.

That is not my homework.
I just want to know the usge of "system()" because I found the system function is like this:int system(char *command)

It is ok when executing command like "dir" that contains no argument.
But I don't know how to do if the command contains arguments(something like what I asked)
Anyway, thanks a lot.
 

Re: exec and system in C

exec() and system() are both Unix system calls.

The difference is that system() can be used to execute any unix command as if you type it at a shell command prompt. You just pass a single string.

e.g. in your C code

system("xterm");

When the system is executed, an xterm will be launched. Default shell is sh so only those command known by shell can be run.

exec() can do the same but it gives you more control. You can specify path to an application and pass arguments to it. For example, if exec() fails to lauch the xterm, the path you specified could be wrong. Like I said, more control.
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…