简体   繁体   中英

C - execve function with touch command not working

I am trying to run touch command via execve(), here is my code:

#include <stdio.h>
#include <unistd.h>

int main()
{
char * c[2]={"/usr/bin/touch","test.txt"};
execve(c[0],c,NULL);
return 0;   
} 

But it doesn't seem like the file is being touched or the date isn't being updated. Somebody help me.

The last element of the array needs to be NULL, so that the exec call can figure out the length of the array.

So change

char * c[2]={"/usr/bin/touch","test.txt"};

to

char * c[3]={"/usr/bin/touch","test.txt",NULL};

You can also use system(); function Just put your command line in parameter like :

system("touch test.txt");

or you also can use fopen with flag "a" like :

FILE *fp = fopen("test.txt", "a");

flag "a" open the file passed as paramater (in our case "test.txt" and if it doesn't exist, it is created)

Man system : http://manpagesfr.free.fr/man/man3/system.3.html

Man Fopen : http://manpagesfr.free.fr/man/man3/fopen.3.html

Have a good day!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM