Home > database >  C system() function
C system() function

Time:06-07

I'm trying to create a file in linux and give it executable rights using system() function in a C program. Here is the code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[], char *envp[]){
char s[100];
strcpy(s, "touch ");
strcpy(s, argv[1]);
strcpy(s, "; chmod a x ");
strcpy(s, argv[1]);
system(s);
return 0;
}

But when I call compiled file with argument "abs" for example (consider I want "abs" as the name of the file to be created) it gives such output:

sh: 1: abs: not found

How can it be fixed? It's important that I have to use C programming and system() function.

CodePudding user response:

It seems that answer is not understandable for future readers, let me try to explain what is the difference between strcpy and strcat

  • strcpy() copies one string into another.
  • strcat() function concatenates string by appending source string to destination string.

In the original code, every time a "strcpy" function was called, a previous value in the buffer was overridden.

char s[100];
strcpy(s, "touch "); // s = touch
strcpy(s, argv[1]); // s = abc (argv[1] value)
strcpy(s, "; chmod a x "); // s = ; chmod a x 
strcpy(s, argv[1]); // s = abc (argv[1] value)
system(s); // execute s = abc

And finally, since "s" is "abc" system() function tries to execute it, which is producing the following error:

sh: 1: abs: not found

In the modified version, instead of overwriting the previous value, the new value is appended to the buffer.

char s[100];
strcpy(s, "touch "); // s = touch
strcat(s, argv[1]); // s = touch abc
strcat(s, "; chmod a x "); // s = touch abc; chmod a x
strcat(s, argv[1]); // s = touch abc; chmod a x abc
system(s); // execute s = touch abc; chmod a x abc

CodePudding user response:

The code should be changed to the following:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[], char *envp[]){
char s[100];
strcpy(s, "touch "); //s = "touch "
strcat(s, argv[1]); //s = "touch "   argv[1]
strcat(s, "; chmod a x "); //s = "touch "   argv[1]   "; chmod a x " 
strcat(s, argv[1]); //s =  "touch "   argv[1]   "; chmod a x "   argv[1]
system(s); //system("touch "   argv[1]   "; chmod a x "   argv[1])
return 0;
}

Thanks a lot to commentators!

  • Related