main函数也可以传递参数的,大家都清楚,但是argv[][]这个是字符串,我们有时候要传递整数怎么办?

答:把字符串转换成整形。比如下文代码中,关键代码:  else if ((argc == 2) && (argv[1][0] == '1')) ,执行的命令行是:./a.out 1.

即就是2个参数,argv[0] 是./a.out,argv[1]是“1”,那argv[1][0]就是'1',注意这里的单双引号,是指字符串和字符。依次类推,如果执行的命令行是./a.out 1234,即传递的整形是1234,那value=1000*argv[1][0]+100*argv[1][1]+10*argv[1][2]+argv[1][3].

说明:

全文代码目的是为了让程序打印记录到日志文件的。

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>


#define LOG_FILE_NAME "./log_file.txt"

FILE *Fd1 = 0;


void SetFileHeader(void)
{
long len = 0;
len = ftell(Fd1);
if (len > 10000)
{
fseek(Fd1, 0, SEEK_SET);
}
}

void OpenFile(void)
{
Fd1 = fopen(LOG_FILE_NAME, "w+");
if (Fd1 != NULL)
{
SetFileHeader();
fprintf(Fd1, "faied to open!\n");
}
else
{
exit(-1);
}
}

void CloseFile(void)
{
fclose(Fd1);
}

void *func1(void *arg)
{
while(1)
{
SetFileHeader();
fprintf(Fd1, "this is 1 test!\n");
}
}
void *func2(void *arg)
{
while(1)
SetFileHeader();
fprintf(Fd1, "this is 2 test!\n");
}
}
void *func3(void *arg)
{
while(1)
{
SetFileHeader();
fprintf(Fd1, "this is 3 test!\n");
}
}
void *func4(void *arg)
{
while(1)
{
SetFileHeader();
fprintf(Fd1, "this is 4 test!\n");
}
}
void *func5(void *arg)
{
while(1)
{
SetFileHeader();
fprintf(Fd1, "this is 5 test!\n");
}
}
void *func6(void *arg)
{
while(1)
{
SetFileHeader();
fprintf(Fd1, "this is 6 test!\n");
}
}
void *func7(void *arg)
{
while(1)
{
SetFileHeader();
fprintf(Fd1, "this is 7 test!\n");
}
}

int main(int argc, char **argv)
{
int ret = 0;

OpenFile();

if (argc == 1)
{
printf("just an a,out!\n");
}
else if ((argc == 2) && (argv[1][0] == '1'))
{
printf("argv[1][0] = %c\n", argv[1][0]);
}
else
{
printf("argc = %d, argv[1][0] = %c\n", argc, argv[1][0]);
}
pthread_t t1;
pthread_t t2;
pthread_t t3;
pthread_t t4;
pthread_t t5;
pthread_t t6;
pthread_t t7;

pthread_create(&t1, NULL, func1, NULL);
pthread_create(&t2, NULL, func2, NULL);
pthread_create(&t3, NULL, func3, NULL);
pthread_create(&t4, NULL, func4, NULL);
pthread_create(&t5, NULL, func5, NULL);
pthread_create(&t6, NULL, func6, NULL);
pthread_create(&t7, NULL, func7, NULL);

while(1)
{
sleep(1);
}
CloseFile();
}