I am trying to make a few directories and files using the system call. ex)

system("mkdir directory3");

I am having trouble getting started. This is what I have so far:

#include <stdio.h>
int main(int argc, const char * argv[])
    system(“mkdir dir1”);
    system(“mkdir dir2”);
    system(“mkdir dir3);
    system(touch file1”);
    system(“touch file2”);
    system(“cd dir1”);
    system(“mkdir dir4”);
    system(“cd dir4”);
    system(“touch file4”);

would this be the right format to go with?

  • Just write a shell script. – Kusalananda Feb 5 '17 at 19:41
  • @Kusalananda is correct that a shell script will be much easier, but if you really need to do this from a C program, You may want to edit the post to explain what your 'trouble' is. And then ask the moderator to migrate the post to StackOverflow. – Stephen Rauch Feb 5 '17 at 19:49
  • Can you clarify what you mean by "right format"? Does it have to be a C program? Functions in any language will eventually end up as system calls; how high or low do you want to go? What is the actual goal here: learning a language? – Jeff Schaller Feb 5 '17 at 20:22
  • 2
    I'm voting to close this question as off-topic because it appears to be a C programming question (and needs clarification at the least). – Michael Homer Feb 5 '17 at 23:54

I assume you tested your code before posting (or maybe you didn't, since it contains a missing quote, which would be a syntax error) and discovered that everything except the cd commands basically works.

The cd commands won't work because you are calling an external process, changing its working directory, and then the external command terminates immediately afterwards, so the command does not have any effect.

Besides the fact that the other commands do work, you should not do it that way. All of the commands you are invoking (mkdir, cd, and touch) can be done in one or two C function calls (actually, system calls) so there is really no point in incurring the performance and security penalty of running them as external commands.

system("mkdir foo") → mkdir("foo", 0777)
system("touch foo") → close(open("foo", O_WRONLY|O_CREAT, 0777))

(Error checking is, of course, left as an exercise to the reader.)

Not the answer you're looking for? Browse other questions tagged or ask your own question.