简体   繁体   中英

using integers inside “ ” block in C

I am using system() func to use omxplayer in linux like system("omxplayer /home/path/1.mp3'); , and I have many mp3 files named like 1.mp3 2.mp3 . I am going to play these mp3 files randomly using rand() function. I am doing like;

switch(randnum)
{
    case 1:
        system("omxplayer /home/path/1.mp3");
    case 2: 
        system("omxplayer /home/path/2.mp3");
    ...
}

and I'm wondering that is it possible that doing like

system("omxplayer /home/path/randnum.mp3");

is this possible?

You could make a random number:

int randomNum = (rand() % UPPER_LIMIT) + 1;

And then create and copy the required string into it using sprintf() or snprintf() :

char buffer[100];
sprintf(buffer, "omxplayer /home/path/%d.mp3", randomNum);

or

char buffer[100];
snprintf(buffer, sizeof buffer, "omxplayer /home/path/%d.mp3", randomNum);

The difference between sprintf() and snprintf() is that snprintf() , unlike sprintf() , requires the size of the buffer as its second argument. This is done for preventing buffer overflows. Thus, snprintf() is better than sprintf() because of the extra security.

And finally, call system() with buffer :

system(buffer);

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