2013-10-15 125 views
0

试图使下面的c代码工作,但每次我给它一个文件来返回它的大小说文件名是空的。我已经试过optarg总是返回空

例如命令行:

Question7 -h -t -f question8.c

不管,它返回OPTARG为空。我不确定为什么会发生这种情况。

#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); 
     } 
    } 
} 

回答

1

当你-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; 
} 
+0

,使一个很大的意义,但现在我得到一个coupel多个错误代码: GCC:无法识别的选项“-h” CC1:错误:无法识别的命令行选项“-f” CC1:错误:无法识别的命令行选项“-f” –

+0

听起来好像你试图用选项'-f'和'-h'运行编译器,而不是你的程序。 –

+0

就是这样,谢谢。 –