C言語プログラミングTips
数値(int)を文字列(char*)に変換
#include <string.h>
void IntToString(int i_number, char **o_str)
{
char tempStr[16];
memset(tempStr, 0x00, 16);
sprintf(tempStr, "%d", i_number);
*o_str = malloc(strlen(tempStr)+1);
memset(*o_str, 0x00, strlen(tempStr)+1);
sprintf(*o_str, "%d", i_number);
}
int main(void) {
char *str = NULL;
IntToString(100, &str);
printf("str:%s\n",str);
return EXIT_SUCCESS;
}
よくあるケアレスミス
・ポインタでもらった文字列のsizeof(=4byteしかとれない・・・)
pthread
void func(){
pthread_attr_t attr; //デタッチ状態にする必要が無ければ不要
pthread_t tid;
struct paramStruct *childFuncArg;
pthread_attr_init(&attr); //デタッチ状態にする必要が無ければ不要
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); //デタッチ状態にする必要が無ければ不要
pthread_create(&tid, &attr, (void*)childFunc, (void*)childFuncArg); //デタッチ状態にする必要が無ければ2ndParamは NULL
pthread_attr_destroy(&attr); //デタッチ状態にする必要が無ければ不要
return;
}
mallocで確保されたメモリを知る
#include <malloc.h>
char *data;
data = (char *)malloc(100);
int size = malloc_usable_size(data); // dataはmallocによって返されたポインタ
Cプログラミング内でコマンド実行(例:プロセス内のメモリリーク調査)を行う。
char command[256];
sprintf( command, "grep VmSize /proc/%d/status", getpid() );
system( command );
文字列初期化
char buf[32];
memset(buf, 0, sizeof(buf));
ファイルサイズを調べる
#include <stdio.h>
long fsize(const char *filename)
{
FILE *stream = fopen(filename, "rb");
long size;
for (size = 0; getc(stream) != EOF; size++)
;
return size;
}
ファイルサイズを調べる(UNIXならば・・・)
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(){
struct stat buf; /* ファイル情報の格納領域 */
if ((stat("sample.c", &buf)) != 0) {
perror("ファイルの情報は取得できませんでした。\n");
exit(1);
}
printf("ファイルの大きさ: %ld バイト\n", buf.st_size);
printf("更新時刻 : %s\n", ctime(&buf.st_atime));
return 0;
}
文字列からUnixTimeを求める。
#include <time.h>
int i = 0;
char date[] = "2010-04-01";
char *tempStr[3];
struct tm timeStr;
time_t unixTime;
memset(&timeStr, 0x00, sizeof(timeStr));
printf("sizeof:tempStr:%d\n",sizeof(tempStr));
printf("struct tm:%s\n", asctime(&timeStr));
tempStr[i] = strtok(date, "-");
for(i=1; i<3; i++)
{
tempStr[i] = strtok(NULL, "-");
}
timeStr.tm_year = atoi(tempStr[0]) - 1900;
timeStr.tm_mon = atoi(tempStr[1]) - 1;
timeStr.tm_mday = atoi(tempStr[2]);
printf("struct tm:%s\n", asctime(&timeStr));
unixTime = mktime(&timeStr);
printf("unixTime:%d\n", (int)unixTime);
※ mktimeは入力値をlocaltimeとして扱い、unixtimeに変換する。
入力値をgmtとして扱ってほしい場合は、mktime後にその差分だけ加算(減算)しなければならない。
例: unixTime = mktime(&timeStr) + 9*3600;
最終更新:2010年08月06日 15:34