本文轉至http://blog.csdn.net/joeblackzqq/article/details/6934921
在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;
- }