当前位置:首页 > 问答大全 > c语言代码求助,高手请进。

c语言代码求助,高手请进。

被浏览: 0次 2023年06月23日 15:32
热门回答(3个)
游客1

#include
#include
#include
int main(int argc, char *argv[]) //argc 是参数个数,argv 是命令行参数
{

int nflag;
if (*++argv && !strcmp(*argv, "-n"))
//指向衡备下一个参物拦枝数,并判断argv所指向的参数是否与“-n”相等,如果相等,执行以下程序

{
++argv;
nflag = 1;
}

else //如果不相等
nflag = 0;

while (*argv)
{
printf("%s", *argv); //打印该参数
if (*++argv) putchar(' '); //指向下一个参数,并输出空格
}
//实际上while部分就是依次打印每个参数,中间用空格隔开

if (!nflag) putchar('\n'); //nflag=0时,输出换行

exit(0); //正常退出程序

}

程序运行之前需要运行cmd进入命令提示符,将路径设置到该执行程序所在的文件夹,接下来输入参数,
格式是<执行文件名>空格<参数1>空罩敏格<参数2>......
如程序名为1.exe,就输入 1.exe 参数1 参数2......参数n
则argc=n+1;argv[0]=“1.exe”;argv[1]=参数1......

游客2

呃.....再加一个行不?

#include
#include
#include
#include
#include
#include
#include
#include
#include

void usage()
{

(void)fprintf(stderr, "usage: sleep seconds\n");

exit(1);

}

void alarmhandle(i)
{

_exit(0);

}

int main(argc, argv)
{

char *arg, *temp;

double val, ival, fval;

struct timespec ntime;

int fracflag;

int ch;

setlocale(LC_ALL, "");

(void)signal(SIGALRM, alarmhandle);

while ((ch = getopt(argc, argv, "")) != -1)

switch(ch)
{

case '亏春?':

default:

usage();

}

argc -= optind;

argv += optind;

if (argc != 1) usage();

fracflag = 0;

arg = *argv;

for (temp = arg; *temp != '\0'; temp++)

if (!isdigit(*temp)) fracflag++;

if (fracflag)

{

val = atof(arg);

if (val <= 0) exit(0);

ival = floor(val);

fval = (1000000000 * (val-ival));

ntime.tv_sec = ival;

ntime.tv_nsec = fval;

}

else
{

ntime.tv_sec = atol(arg);

if (ntime.tv_sec <哪空含= 0)

exit(0);

ntime.tv_nsec = 0;

}

(void)nanosleep(&ntime, NULL);

exit(0);

}

游客3

朋友问到主函数main中变量( int argc,char **argv )的含义问题,这里

我给在网上找了个解释,比较清楚,贴在这里汪虚,望有所启发。

看过多个Linux下的软件的源代码,发现很多项目都有main(int argc,char *argv[])或者 ( int argc,char **argv ),

在网上找到如下的说明。

我刚接触到这两个变量时,根本不知道它们是用来做什么的,我想很多人也跟我一样,刚看到这两个变量时也是稀里糊涂的。

其实: int main(int argc,char *argv[]) 是 UNIX 和 Linux 中的标准写法,而 int main() 只是 UNIX 及哪迹 Linux 默许的用法..

那究竟 argc,argv[] 有何之用呢?下面看个例子 test_argc.c 就会明白它们的用法了:

#include
#include

int main(int argc,char *argv[])
{
if( argc==1 || argc>2 )
{
printf("请输入想要编辑的文件名如: ./test_argc filename \n");
}
if( argc==2 )
{
printf("编辑 %s\n",argv[1]);
}
exit (0);
}

编译该程序:gcc -o test_argc test_argc.c
运行:# ./test_argc
结果: 请输入想要编辑的文件名如:./test_argc fille
运行:# ./困缓燃test_argc test_argc.txt
结果: 编辑 test_argc.txt

看到这里 argc,argv[] 如何用就很明白了,argc 是外部命令参数的个数,argv[] 存放各参数的内容,如上例:执行 ./test_argc 时,argc 为1,
argv[0] 为 ./test_argc .而执行 ./test_argc test_argc.txt 时,argc 的值为 2,
argv[0] 为 ./test_argc, argv[1] 为 test_argc.txt .