Using the rm command in a c program, using the system () function in stdlib.h

I am trying to use a command rmin the main procedure to delete a file that I accepted a command line argument. The value is stored in argv[2], I tried to use

system("rm argv[2]");

system("rm ./argv[2]");

system("rm $HOME/argv[2]");

But it gives me a mistake saying

"cannot locate file argv [2]"

The file name is stored in argv[2]since I checked it.

Someone please guide me!

+3
source share
9 answers

Why not use remove or unlink instead ? system("rm ...")

remove(argv[2]); or unlink(argv[2]);


Refresh in case to system("rm ...")be used

system("rm ..."), ZelluX , , argv[2]. argv[2] snprintf strncpy. , , , argv[2].

stat, , argv[2] , , .

:

stat, , argv[2] asprintf, .

char *p;
struct stat st;

if (stat(argv[2], &st) == 0 && S_ISREG(st->st_mode))
{
    if (asprintf(&p, "rm %s", argv[2]) != -1)
    {
        system(p);
        free(p);
    }
}
+15

"argv [2]" "rm./argv[2]" - , , argv [2], strcpy() sprintf() "rm./" , argv [2].

+8

argv [2] , . strcpy , argv [2] , rm, . .

+2

rm command, C,

#include <stdio.h>
#include <dirent.h>
int  main()
{
        struct dirent *d;
        DIR *dir;
        char buf[256];
        dir = opendir("mydir");
        while(d = readdir(dir))
        {               
                sprintf(buf, "%s/%s", "mydir", d->d_name);
                remove(buf);
        }
        return 0;

}
+2

. unlink (2) ( unistd.h), ().

+2

. argv [2] .

:

char buf[256];

buf[255] = '\0';
if (snprintf(buf, 255, "rm %s", argv[2]) != -1) {
    system(buf);
}
+1

system (, ), . , argv[2] "-rf /".: -)

+1

, argv [2] , argv [2], . sprintf(), ()

char str[100];
sprintf(str,"rm %s",argv[2]);
system(str);
0

This is actually argv[2]a string, and you use it as the file name to use as the string you want to concatenate. The reason you cannot find a file with a name argv[2]instead of a file name is in char array argv[2]. Try different concatenation methods.

0
source

Source: https://habr.com/ru/post/1732481/


All Articles