在linux写了个简单的C程序,里面用到了itoa,但是编译时提示“undefined reference to `itoa'”,本以为加上-lc就行了,可结果还是一样。上网发现,有人说这个函数在linux中是不存在的,一般用sprintf来代替。看下面代码及注释吧:
#include <stdio.h>
#include <stdlib.h>
//#include <unistd.h>
#include <string.h>
int num = 0;
char namebuf[100];
char prefix[] = "/tmp/tmp/p";
char* gentemp()
{
int length, pid;
pid = getpid();
strcpy(namebuf, prefix);
length = strlen(namebuf);
//itoa(pid, &namebuf[length], 10); // Unix版本:itoa()在头文件<stdlib.h>中不存在
sprintf(namebuf+length, "%d", pid); // 使用sprintf将整数转换成字符串
strcat(namebuf, ".");
length = strlen(namebuf);
printf("before do...while\n");
char command[1024] = {0};
do
{
//itoa(num++, &namebuf[length], 10);
sprintf(namebuf+length, "%d", num++);
sprintf(command, "touch %s", namebuf); // 通过touch来创建文件
system(command);
printf("command = %s, namebuf[%d]=%d\n", command, num-1, num-1);
} while (num < 50 && access(namebuf, 0) != -1); // access判断文件是否存在
printf("end of do...while\n");
return namebuf;
}
int main( void )
{
char *p = gentemp();
printf("%s\n", p);
return 0;
}