简体   繁体   English

在C中使用“”块内的整数

[英]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; 我正在使用system()函数在Linux中像system("omxplayer /home/path/1.mp3');一样使用omxplayer,并且我有很多mp3文件,如1.mp3 2.mp3 。我使用rand()函数随机播放mp3文件。

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() : 然后使用sprintf()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. sprintf()snprintf()之间的区别在于snprintf()sprintf()不同,它需要缓冲区的大小作为第二个参数。 This is done for preventing buffer overflows. 这样做是为了防止缓冲区溢出。 Thus, snprintf() is better than sprintf() because of the extra security. 因此,由于额外的安全性, snprintf()sprintf()更好

And finally, call system() with buffer : 最后,使用buffer调用system()

system(buffer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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