如何解决使用mytee合并makefile时如何解决错误
当我使用getopt API完成代码(mytee.c)以便在UNIX中编写实现命令并使用make test测试文件时,我得到以下消息:
"make test
gcc -o mytee mytee.c
make test1
make[1]: Entering directory '/home/programmer/proj1'
./mytee -v
usage: mytee [-av] _filename_
make[1]: Leaving directory '/home/programmer/proj1'
make test2
make[1]: Entering directory '/home/programmer//proj1'
cat mytee.c | ./mytee mytee.fout > mytee.out
Expected argument after options
make[1]: *** [Makefile:32: test2] Error 1
make[1]: Leaving directory '/home/programmer/proj1'
make: *** [Makefile:21: test] Error 2"
运行测试时,将创建以下文件:mytee.fout mytee.out mytee random.bin
makefile是这样的: [makefile] [1]
当我执行此命令diff mytee.fout mytee.c
时,收到以下消息:0a1,77。在此处输入图片说明。为了正确运行,我应该怎么做才能解决此错误?
我的代码在这里:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<assert.h>
#define USAGE_MESSAGE "usage: mytee [-av] _filename_"
/* globals and externs go here */
int main(int argc,char * argv[]) {
int ch ;
int is_verbose = 0 ;
int is_append = 0 ;
char * mode_s = NULL ;
char * filename ;
FILE * f ;
int nsecs =0;
while ((ch = getopt(argc,argv,"va")) != -1) {
switch(ch) {
/*
* modify or add to these case statements
*/
case 'v':
is_verbose = 1 ;
break ;
case 'a':
mode_s= optarg;
is_append = 1 ;
break ;
default:
printf("%s\n",USAGE_MESSAGE) ;
return 0 ;
}
}
argc -= optind;
argv += optind;
if (argc!=1) {
printf("%s\n",USAGE_MESSAGE) ;
return 0 ;
}
filename = argv[0] ;
if (is_verbose) {
printf("%s:%d: openning file %s in mode %s\n",__FILE__,__LINE__,filename,mode_s) ;
}
f = fopen(filename,mode_s) ;
assert(f) ;
while (1) {
while (ch = getchar()&&ch != EOF) {
putchar(ch);
ch = getchar();
}
printf("verbose=%d; append=%d; optind=%d\n",is_verbose,is_append,optind);
printf("name argument = %s\n",argv[optind]);
break;
}
if (optind >= argc) {
fprintf(stderr,"Expected argument after options\n");
exit(EXIT_FAILURE);
}
return 0; }
makefile就在这里
make mytee
test: mytee
make test1
make test2
make clean
@echo "*** ${GREEN}PASSED the test ${NC}***"
mytee: mytee.c
gcc -o mytee mytee.c
test1: mytee
./mytee -v
test2: mytee
cat mytee.c | ./mytee mytee.fout > mytee.out
diff mytee.fout mytee.c
diff mytee.c mytee.out
test3: mytee
dd if=/dev/urandom bs=1 count=4096 of=random.bin
cat random.bin | ./mytee mytee.fout > mytee.out
diff random.bin mytee.fout
diff random.bin mytee.out
mytest: mytee
@echo "student adds tests,for instance,"
@echo "* mytee called without argument,"
@echo "* mytee called with -a option"
clean:
-rm mytee.fout mytee.out mytee random.bin
解决方法
参数列表包括程序名称。该程序的第一个参数在argv[1]
中。
所以如果你打电话
./mytee
你会得到
argc: 1
argv[0]: "./mytee"
产生错误的命令是
./mytee mytee.fout
您将得到
argc: 2
argv[0]: "./mytee"
argv[1]: "mytee.fout"
但是您正在将argc
与1(而非2)进行比较。
注意:您可以通过阅读文档来找到这些东西,或者通过编写像这样的简单测试来发现这些东西:
#include <stdio.h>
int main(int argc,char *argv[]) {
int i;
for (i = 0; i < argc; ++i) {
printf("%d: \"%s\"\n",i,argv[i]);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。