【转】关于getopt和<unistd.h>

本文详细介绍了getopt函数在Linux及Windows平台上的使用方法,包括如何解析命令行参数、处理长选项与短选项等。提供了丰富的示例代码帮助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Linux下开发的C程序都需要头文件unistd.h,但VC中没有个头文件
这个是UNIX/Linux的文件,如果实在需要可以考虑安装cygwin。
这是unix系统的头文件,windows没有的。

 
http://vopit.blog.51cto.com/2400931/440453 点击打开链接
getopt(分析命令行参数)  
 
相关函数表头文件
        #include<unistd.h>
定义函数
        int getopt(int argc,char * const argv[ ],const char * optstring);
函数说明
        getopt()用来分析命令行参数。参数argc和argv是由main()传递的参数个数和内容。参数optstring 则代表欲处理的选项字符串。此函数会返回在argv 中下一个的选项字母,此字母会对应参数optstring 中的字母。如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符,如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可。
 
短参数的定义
       getopt()使用optstring所指的字串作为短参数列表,象"1ac:d::"就是一个短参数列表。短参数的定义是一个'-'后面跟一个字母或数字,象-a, -b就是一个短参数。每个数字或字母定义一个参数。 
  其中短参数在getopt定义里分为三种:
  1. 不带值的参数,它的定义即是参数本身。
  2. 必须带值的参数,它的定义是在参数本身后面再加一个冒号。
  3. 可选值的参数,它的定义是在参数本身后面加两个冒号 。
  在这里拿上面的"1ac:d::"作为样例进行说明,其中的1,a就是不带值的参数,c是必须带值的参数,d是可选值的参数。
  在实际调用中,'-1 -a -c cvalue -d', '-1 -a -c cvalue -ddvalue', '-1a -ddvalue -c cvalue'都是合法的。这里需要注意三点:
  1. 不带值的参数可以连写,象1和a是不带值的参数,它们可以-1 -a分开写,也可以-1a或-a1连写。
  2. 参数不分先后顺序,'-1a -c cvalue -ddvalue'和'-d -c cvalue -a1'的解析结果是一样的。
  3. 要注意可选值的参数的值与参数之间不能有空格,必须写成-ddvalue这样的格式,如果写成-d dvalue这样的格式就会解析错误。

返回值
   getopt()每次调用会逐次返回命令行传入的参数。
   当没有参数的最后的一次调用时,getopt()将返回-1。
    当解析到一个不在optstring里面的参数,或者一个必选值参数不带值时,返回'?'。
   当optstring是以':'开头时,缺值参数的情况下会返回':',而不是'?' 。

范例 

  
  1. #include <stdio.h>  
  2. #include <unistd.h>  
  3.  
  4. int main(int argc, int *argv[])  
  5. {  
  6.         int ch;  
  7.         opterr = 0;  
  8.         while ((ch = getopt(argc,argv,"a:bcde"))!=-1)  
  9.         {  
  10.                 switch(ch)  
  11.                 {  
  12.                         case 'a':  
  13.                                 printf("option a:'%s'\n",optarg);  
  14.                                 break;  
  15.                         case 'b':  
  16.                                 printf("option b :b\n");  
  17.                                 break;  
  18.                         default:  
  19.                                 printf("other option :%c\n",ch);  
  20.                 }  
  21.         }  
  22.         printf("optopt +%c\n",optopt);  
  23. }  

执行:

  
  1. $ ./getopt -a  
  2. other option :?  
  3. optopt +a  
  4. $ ./getopt -b  
  5. option b :b  
  6. optopt +  
  7. $ ./getopt -c  
  8. other option :c  
  9. optopt +  
  10. $ ./getopt -d  
  11. other option :d  
  12. optopt +  
  13. $ ./getopt -abcd  
  14. option a:'bcd' 
  15. optopt +  
  16. $ ./getopt -bcd  
  17. option b :b  
  18. other option :c  
  19. other option :d  
  20. optopt +  
  21. $ ./getopt -bcde  
  22. option b :b  
  23. other option :c  
  24. other option :d  
  25. other option :e  
  26. optopt +  
  27. $ ./getopt -bcdef  
  28. option b :b  
  29. other option :c  
  30. other option :d  
  31. other option :e  
  32. other option :?  
  33. optopt +f  

 
Windows下使用GetOpt函数使用
http://blog.youkuaiyun.com/fan_hai_ping/article/details/8058811   点击打开链接

GetOpt库下载

GetOpt.h是一个GNU标准库的头文件,它包含一些从命令行上提取参数的工具用于基于文本C/C++应用程序。因为getopt.h不是ANSI C标准库的一部分,getopt必须编译到每个使用它的项目中,或者编译它倒一个静态类,显式的链接到程序中。在Windows下有一个预编译的getopt版本可用使用,其下载网址为:
http://ieng6.ucsd.edu/~cs12x/vc08install/getopt9.zip
把压缩文件中的getopt.h头文件和getopt.lib库文件拷贝到你的计算机中,然后添加这些目录到VC++搜索路径中,以至于getopt库可以像标准库的一部分使用。
注:在CodeProject网站上也提供基于C的GetOpt库实现,下载网址为:
http://www.codeproject.com/Articles/157001/Full-getopt-Port-for-Unicode-and-Multibyte-Microso
         在项目中使用该源代码时,在预编译定义中添加STATIC_GETOPT选项。

使用实例

假如一个应用程序需要下面的短选项和长选项。
短选项有-h,-o filename,-v,所对应的长选项为--help,--outputfilename,--version。为了使用getopt_long函数,需要先定义两个变量。
一个字符串:”ho:v”,因为-o后面有参数filename,因此字符后面需要加“:”。
一个包含长选项字符串的option数组,每个option结构包括4个字段,分别为长选项字符串、标识(是否带参数)、NULL和短选项字符串,最后一个元素全为空,表示结束。
const structoption long_options[] = {
  {“help”, 0, NULL, ‘h’},
{“output”, 1, NULL, ‘o’},
{“version”, 0, NULL, ‘v’},
{NULL, 0, NULL, 0}
};
调用的时候把main中两个参数argc和argv以及上述两个参数传递给getopt_long函数,每次调用getopt_long会解析出一个符号,返回相应的短选项,解析完成返回-1。
如果遇到一个无效的短选项字符,会返回一个‘?’字符,解析到一个长选项并且发现没有参数则返回’:’字符,表示缺乏参数。当 getopt_long() 返回 0 时,longIndex 所指向的整数将设置为当前找到的长选项的索引。
全局变量optarg表示下一个要处理的变量,当getopt_long处理完所有的选项后,optind指向第一个未知的选项索引。代码如下:
#include<getopt.h>                // 包含头文件
#pragma comment(lib,“getopt.lib”)   // 加载静态库文件(Windows)
#include<stdio.h>
#include<stdlib.h>
 
int main(int argc,char**argv)
{
struct globalArgs_t {
    int noIndex;                /* -I option */
    char *langCode;             /* -l option */
    const char *outFileName;    /* -o option */
    FILE *outFile;
    int verbosity;              /* -v option */
    char **inputFiles;          /* input files */
    int numInputFiles;          /* # of input files */
    int randomized;             /* --randomize option */
} globalArgs;
  static const char *optString = "Il:o:vh?";
 
static conststruct option longOpts[] = {
    { "no-index", no_argument, NULL,'I' },
    { "language", required_argument,NULL, 'l' },
    { "output", required_argument,NULL, 'o' },
    { "verbose", no_argument, NULL,'v' },
    { "randomize", no_argument, NULL,0 },
    { "help", no_argument, NULL, 'h'},
    { NULL, no_argument, NULL, 0 }
};
  opt = getopt_long( argc, argv, optString, longOpts, &longIndex );
    while( opt != -1 ) {
        switch( opt ) {
            case 'I':
                globalArgs.noIndex = 1; /* true */
                break;
                
            case 'l':
                globalArgs.langCode = optarg;
                break;
                
            case 'o':
                globalArgs.outFileName = optarg;
                break;
                
            case 'v':
                globalArgs.verbosity++;
                break;
                
            case 'h':   /* fall-through is intentional */
            case '?':
                display_usage();
                break;
 
            case 0:     /* long option without a short arg */
                if( strcmp( "randomize", longOpts[longIndex].name ) == 0 ) {
                    globalArgs.randomized = 1;
                }
                break;
                
            default:
                /* You won't actually get here. */
                break;
        }
        
        opt = getopt_long( argc, argv, optString, longOpts, amp;longIndex );
    }
}
 
注:getopt()函数的处理过程getopt_long相似,就是缺少long_options参数。
注:在Linux中getopt_long()函数在 getopt.h 头文件(而非 unistd.h)中,getopt()在<unistd.h>头文件

In file included from cryptlib.c:117:0: cryptlib.h:62:21: fatal error: stdlib.h: No such file or directory # include <stdlib.h> ^ compilation terminated. mem.c:59:19: fatal error: stdio.h: No such file or directory #include <stdio.h> ^ compilation terminated. mem_clr.c:60:20: fatal error: string.h: No such file or directory #include <string.h> ^ compilation terminated. mem_dbg.c:112:19: fatal error: stdio.h: No such file or directory #include <stdio.h> ^ compilation terminated. In file included from cversion.c:59:0: cryptlib.h:62:21: fatal error: stdlib.h: No such file or directory # include <stdlib.h> ^ compilation terminated. In file included from ex_data.c:141:0: cryptlib.h:62:21: fatal error: stdlib.h: No such file or directory # include <stdlib.h> ^ compilation terminated. cpt_err.c:62:19: fatal error: stdio.h: No such file or directory #include <stdio.h> ^ compilation terminated. In file included from uid.c:56:0: ../include/openssl/crypto.h:120:21: fatal error: stdlib.h: No such file or directory # include <stdlib.h> ^ compilation terminated. o_time.c:65:20: fatal error: string.h: No such file or directory #include <string.h> ^ compilation terminated. o_str.c:60:19: fatal error: ctype.h: No such file or directory #include <ctype.h> ^ compilation terminated. o_dir.c:60:19: fatal error: errno.h: No such file or directory #include <errno.h> ^ compilation terminated. In file included from o_fips.c:59:0: cryptlib.h:62:21: fatal error: stdlib.h: No such file or directory # include <stdlib.h> ^ compilation terminated. In file included from o_init.c:56:0: ../e_os.h:468:28: fatal error: unistd.h: No such file or directory # include OPENSSL_UNISTD ^ compilation terminated. getenv.c:14:20: fatal error: stdlib.h: No such file or directory #include <stdlib.h> ^ compilation terminated. Makefile:138: recipe for target 'local_depend' failed make[1]: *** [local_depend] Error 1 make[1]: Leaving directory '/home/holand/work/openssl-OpenSSL_1_0_2u/crypto' Makefile:483: recipe for target 'depend' failed make: *** [depend] Error 1
06-13
extern "C" { #include <libavformat/avformat.h> #include <libavdevice/avdevice.h> #include <libavutil/opt.h> #include <libavcodec/avcodec.h> #include <libswscale/swscale.h> #include "libavutil/imgutils.h" #include "unistd.h" #include <cstdlib> #include <assert.h> #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <pthread.h> #include <signal.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/poll.h> #include <time.h> #include <unistd.h> #include <sys/poll.h> #include <time.h> #include <unistd.h> } #include "sample_comm.h" #include "rtsp_demo.h" #include <vector> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; #define DISP_WIDTH 1920 #define DISP_HEIGHT 1080 void Init_ISP(void) { RK_BOOL multi_sensor = RK_FALSE; const char *iq_dir = "/etc/iqfiles"; rk_aiq_working_mode_t hdr_mode = RK_AIQ_WORKING_MODE_NORMAL; //hdr_mode = RK_AIQ_WORKING_MODE_ISP_HDR2; SAMPLE_COMM_ISP_Init(0, hdr_mode, multi_sensor, iq_dir); SAMPLE_COMM_ISP_Run(0); } int main(int argc,char * argv[]) { system("RkLunch-stop.sh"); //1:初始化 ISP RK_BOOL multi_sensor = RK_FALSE; const char *iq_dir = "/etc/iqfiles"; rk_aiq_working_mode_t hdr_mode = RK_AIQ_WORKING_MODE_NORMAL; //hdr_mode = RK_AIQ_WORKING_MODE_ISP_HDR2; SAMPLE_COMM_ISP_Init(0, hdr_mode, multi_sensor, iq_dir); SAMPLE_COMM_ISP_Run(0); printf("初始化 ISP 成功!\r\n"); //2:初始化 RKMPI if (RK_MPI_SYS_Init() != RK_SUCCESS) { RK_LOGE("rk mpi sys init fail!"); return -1; } printf("初始化 MPI 系统成功!\r\n"); /////////////////////////// //初始化ai音频 AIO_ATTR_S aiattr = {0}; aiattr.enBitwidth = AUDIO_BIT_WIDTH_16; aiattr.enSamplerate = AUDIO_SAMPLE_RATE_8000; aiattr.enSoundmode = AUDIO_SOUND_MODE_STEREO; aiattr.soundCard.bitWidth = AUDIO_BIT_WIDTH_16; aiattr.soundCard.channels = 2; aiattr.soundCard.sampleRate = 8000; aiattr.u32ChnCnt = 1; aiattr.u32EXFlag = 0; aiattr.u32FrmNum = 8; aiattr.u32PtNumPerFrm = 1024; RK_U8 nam[64] = "hw:0,0"; strcpy((char *)aiattr.u8CardName,(const char *)nam); int ret = RK_MPI_AI_SetPubAttr(0,&aiattr); if (ret) { printf("ERROR: create AI error! ret=%d\n", ret); return ret; } ret = RK_MPI_AI_Enable(0); if (ret) { printf("ERROR: RK_MPI_AI_Enable error! ret=%d\n", ret); return ret; } ret = RK_MPI_AI_EnableChn(0,0); if (ret) { printf("ERROR: RK_MPI_AI_EnableChn error! ret=%d\n", ret); return ret; } AENC_CHN_ATTR_S aencattr; //memset(&aencattr, 0, sizeof(AENC_CHN_ATTR_S)); aencattr.enType = RK_AUDIO_ID_PCM_ALAW; aencattr.stCodecAttr.enBitwidth = AUDIO_BIT_WIDTH_16; aencattr.stCodecAttr.enType = RK_AUDIO_ID_PCM_ALAW;// aencattr.stCodecAttr.u32Bitrate = 64000;// aencattr.stCodecAttr.u32Channels = 2; aencattr.stCodecAttr.u32SampleRate = 8000; aencattr.u32BufCount = 10; //aencattr.stCodecAttr.u32Bitrate = 64000; ret = RK_MPI_AENC_CreateChn(0,&aencattr); if (ret) { printf("ERROR: create AENC error! ret=%d\n", ret); return ret; } // 定义源(VI)目标(VENC)通道信息 MPP_CHN_S asrc; // 源:AI设备 MPP_CHN_S adst; // 目标:AENC编码器 // 配置源通道(VI设备0的通道0) asrc.enModId = RK_ID_AI; // 模块ID:AI asrc.s32ChnId = 0; // 通道ID asrc.s32DevId = 0; // 设备ID // 配置目标通道(VENC通道0) adst.enModId = RK_ID_AENC; // 模块ID:AENC adst.s32ChnId = 0; // 通道ID adst.s32DevId = 0; // 设备ID // 绑定AIAENC //RK_MPI_SYS_Bind(&asrc,&adst); // 修复:添加返回值判断 ret = RK_MPI_SYS_Bind(&asrc, &adst); if (ret != RK_SUCCESS) { printf("ERROR: AI与AENC绑定失败!ret=%d\n", ret); return ret; } // rtsp init rtsp_demo_handle g_rtsplive = NULL; rtsp_session_handle g_rtsp_session; g_rtsplive = create_rtsp_demo(554); g_rtsp_session = rtsp_new_session(g_rtsplive, "/live/test"); rtsp_set_audio(g_rtsp_session,RTSP_CODEC_ID_AUDIO_G711A,NULL,0);///加上音频推流初始化 rtsp_sync_audio_ts(g_rtsp_session, rtsp_get_reltime(), rtsp_get_ntptime());///加上音频推流初始化 AUDIO_STREAM_S aencFrame;//音频流 ///////////////////////////////// while(1) { //音频rtsp int s32Ret = RK_MPI_AENC_GetStream(0,&aencFrame,-1); printf("运行到GetStream后这里\n"); if(s32Ret == RK_SUCCESS) { printf("获取音频数据且编码成功 当前帧数据长度==%d 当前帧时间戳==%lld\r\n",aencFrame.u32Len,aencFrame.u64TimeStamp); if(g_rtsplive && g_rtsp_session) { //printf("len = %d PTS = %d \n",stFrame.pstPack->u32Len, stFrame.pstPack->u64PTS); void *paData = RK_MPI_MB_Handle2VirAddr(aencFrame.pMbBlk); rtsp_tx_audio(g_rtsp_session, (uint8_t *)paData, aencFrame.u32Len, aencFrame.u64TimeStamp); rtsp_do_event(g_rtsplive); } } s32Ret = RK_MPI_AENC_ReleaseStream(0, &aencFrame); if (s32Ret != RK_SUCCESS) { RK_LOGE("RK_MPI_AENC_ReleaseStream fail %x", s32Ret); } } return 0; } 这个RV1106G3音频推流问题出在哪,为啥拉流没有声音,杀死进程的一瞬间有一点杂声,用的贴片麦克风
最新发布
08-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值