[英]optarg always returns null
试图使以下c代码起作用,但每次我给它一个文件以打乱它的大小时,文件名都为null。
我尝试过的示例命令行:
第7个问题-h -t -f第8个问题c
无论如何,它都返回optarg为null。 我不确定为什么会这样。
#include <stdio.h>
#include <getopt.h>
#include <sys/utsname.h>
#include <time.h>
#include <sys/stat.h>
int main(int argc, char **argv){
char c;
struct utsname uname_pointer;
time_t time_raw_format;
struct stat s;
int hflag = 0;
int tflag = 0;
int fflag = 0;
char *fvalue = NULL;
int index;
int check;
opterr = 0;
while ((check = getopt (argc, argv, "htf:")) != -1){
switch (check) {
case 'h':
hflag = 1;
break;
case 't':
tflag = 1;
break;
case 'f':
fflag = 1;
break;
}
}
if (hflag ==1 ) {
uname (&uname_pointer);
printf("Hostname = %s \n", uname_pointer.nodename);
}
if (tflag ==1 ){
time (&time_raw_format);
printf("the current local time: %s", ctime(&time_raw_format));
}
if (fflag == 1){
if (stat(optarg, &s) == 0){
printf("size of file '%s' is %d bytes\n", optarg, (int) s.st_size);
}else {
printf("file '%s' not found\n", optarg);
}
}
}
当您获得-f
(或'f'
)时,即您读取optarg
:
char *fname = 0;
case 'f':
fname = optarg;
break;
等等optarg
都重新调零,因此,当getopt()
失败并退出循环时,它再次为NULL。 通常,您可以有许多使用选项值的选项,并且单个全局变量不能一次存储所有选项。
#include <stdio.h>
#include <getopt.h>
#include <sys/utsname.h>
#include <time.h>
#include <sys/stat.h>
int main(int argc, char * *argv)
{
char *fname = NULL;
int check;
int hflag = 0;
int tflag = 0;
opterr = 0;
while ((check = getopt(argc, argv, "htf:")) != -1)
{
switch (check)
{
case 'h':
hflag = 1;
break;
case 't':
tflag = 1;
break;
case 'f':
fname = optarg;
break;
}
}
if (hflag == 1)
{
struct utsname uname_pointer;
uname(&uname_pointer);
printf("Hostname = %s \n", uname_pointer.nodename);
}
if (tflag == 1)
{
time_t time_raw_format;
time(&time_raw_format);
printf("the current local time: %s", ctime(&time_raw_format));
}
if (fname != NULL)
{
struct stat s;
if (stat(fname, &s) == 0)
printf("size of file '%s' is %d bytes\n", fname, (int) s.st_size);
else
printf("file '%s' not found\n", fname);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.