• ベストアンサー

ファイル情報の「月」の値を整数値で取得するには?

こんにちは。私は30代の男性です。 下記のサイトに載っていたコーディングなのですが、 http://okuyama.mt.tama.hosei.ac.jp/unix/C/slide93-1.html 「ctime(&filestat.st_mtime)」で取得した「Sat Apr 5」の「月」の値を整数で取得する方法を 考えています(例えば、「Sat 4 5」という感じで)。 何かいい方法はないでしょうか?アドバイスを頂けるとありがたいです。 よろしくお願いします。 #include <sys/types.h> /* stat(), struct stat */ #include <sys/stat.h> /* stat(), struct stat */ #include <stdio.h> /* fprintf(), printf() */ #include <errno.h> /* errno */ #include <string.h> /* strerror() */ #include <stdlib.h> /* exit() */ #include <time.h> /* time_t, ctime() */ int main(void) { struct stat filestat; char path[] = "/path/to/file"; time_t dtime; if(stat(path, &filestat) == -1) { fprintf(stderr, "* Error (%d) [stat: %s]\n", errno, strerror(errno)); exit(errno); } printf("Size: %ld\n", (long)filestat.st_size); printf("Last accessed: %ld, %s", filestat.st_atime, ctime(&filestat.st_atime)); printf("Last modified: %ld, %s", filestat.st_mtime, ctime(&filestat.st_mtime)); dtime = filestat.st_atime - filestat.st_mtime; printf("%ld\n", dtime); exit(0); } 実行例です。 Size: 86555 Last accessed: 1049485323, Sat Apr 5 04:42:03 2003 Last modified: 1049428803, Fri Apr 4 13:00:03 2003 56520

  • DT50
  • お礼率95% (504/530)

質問者が選んだベストアンサー

  • ベストアンサー
  • DT200
  • ベストアンサー率38% (63/164)
回答No.2

ctime() を以下の new_ctime() に置き換えれば期待している文字列が出力される筈です。 char *new_ctime( time_t *tim ) { static char *week[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char buf[ 32 ]; struct tm *lt; lt = localtime( tim ); snprintf( buf, 31, "%s %d %d %02d:%02d:%02d %4d", week[ lt->tm_wday ], /* 曜日 */ lt->tm_mon + 1, /* 月 */ lt->tm_mday, /* 日 */ lt->tm_hour, /* 時間 */ lt->tm_min, /* 分 */ lt->tm_sec, /* 秒 */ lt->tm_year + 1900 ); /* 年 */ return buf; }

DT50
質問者

お礼

返事が遅くなって申し訳ありません。 ご回答ありがとうございました。 参考にさせて頂きます。

その他の回答 (1)

  • Werner
  • ベストアンサー率53% (395/735)
回答No.1

localtimeやgmtimeを使ってtime_t型(st_atimeやst_mtime)をtm構造体に変換すれば tm構造体のメンバから月を取得できます。 http://www9.plala.or.jp/sgwr-t/lib/localtime.html http://www9.plala.or.jp/sgwr-t/lib/gmtime.html

DT50
質問者

お礼

返事が遅くなって申し訳ありません。 ご回答ありがとうございました。 参考にさせて頂きます。

関連するQ&A

  • sys/types.hの必要性について

    #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/stat.h> #include<unistd.h> int main (int argc,char *argv[]) { struct stat buf[2],*p;     if(argc!=3) { fprintf(stderr,"Usage:newer file1 file2\n"); exit(EXIT_FAILURE); } p=buf; if(stat(argv[1],p)<0) { perror("stat"); exit(EXIT_FAILURE); } p++; if(stat(argv[2],p)<0) { perror("stat"); exit(EXIT_FAILURE); } if(buf[0].st_mtime>buf[1].st_mtime) { printf("%s\n",argv[1]); } else { printf("%s\n",argv[2]); } return EXIT_SUCCESS; } 上記のプログラムでは<sys/types.h>を使っていますが、 どこの部分で必要になるのでしょうか? プログラム貼り付けて非常に見づらくてすいません

  • 1秒で動くインターバルタイマ

    こんにちは。私のプログラミング能力が無いために困ってます。 timer_settimeを使って、インターバルが1sのタイマで100s後に終了させたいのですが、できません。環境はRedHatLinux7.1Jです。 下記のプログラムを実行するとtimer_createとtimer_settimerのところで、errno=38 "function not implemented"とでます。原因、どうしたらよいかわかりません。どのように修正したらうごくんでしょうか? 教えてください。 #include <signal.h> #include <time.h> #include <error.h> #include <errno.h> extern int errno; timer_t timerid; struct itimerspec one_minute = { {60, 0}, {0, 0} } ; struct sigaction sigact; struct sigevent sigev; int i,end; void handler() { i++; if (i == 100) end = 1; printf("きてます\n"); } int main() { i=0; end=0; sigact.sa_handler = handler; sigact.sa_flags = 0; if (sigaction(SIGUSR1, &sigact, (struct sigaction *)NULL)== -1) { printf("%d:%s\n",errno,strerror(errno)); exit(1); } sigev.sigev_notify = SIGEV_SIGNAL; sigev.sigev_signo = SIGUSR1; if (timer_create(CLOCK_REALTIME, &sigev, &timerid) == -1) { printf("%d:%s\n",errno,strerror(errno)); exit(1); } if (timer_settime(timerid, 0, &one_minute, (struct itimerspec == -1) { printf("%d:%s\n",errno,strerror(errno)); exit(1); } while (!end){ pause(); } if (timer_delete(timerid) == -1) { perror("timer_delete"); exit(1); } return 0; } 宜しくお願いします。

  • ディレクトリの判別

    FreeBSD5.4でstat()関数のS_ISDIRを使ってディレクトリかどうかを判別したいのですが、 S_ISDIRでは普通のファイルもディレクトリと認識してしまいます。もしご存知の方がいらっしゃいましたら、何卒ご教授くださいませ。 --------------------------------------------- #include <stdio.h> #include <string.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <stdlib.h> int createFileList(char *directoryName){ DIR *directoryId; struct dirent *directoryPointer; struct stat fi; directoryId=opendir(directoryName); while((directoryPointer=readdir(directoryId))!=NULL){ stat(directoryPointer->d_name,&fi); if (!S_ISDIR(fi.st_mode)) printf("%s\n",directoryPointer->d_name); } closedir(directoryId); return 0; } ---------------------------------------------

  • cの標準関数openでNo such a file or directoryが起こっている状況について

    以下のプログラムでエラーとなる要因はどこにあるのでしょうか? #include <fcntl.h> #include <sys\stat.h> #include <sys\types.h> #include <string.h> #include <errno.h> char fname01[64]; //グローバル変数 ここからが、エラーになるプログラム ↓ fh_out = open( &fname01[0], O_CREAT|O_WRONLY|O_BINARY , S_IREAD|S_IWRITE );   if (fh_out == -1){ Application->MessageBox( strerror(errno) , " エラー", MB_OK | MB_ICONEXCLAMATION); ブレイクして、fname01を見た値。c:\\TEST\\d050_g10s187mv174av96bv16.bmp\0

  • Visual Cのstat構造体の動作

    はじめまして。 stat構造体をprintf系の関数で出力するときの異常動作で悩んでいます。 stat関数で読み取った複数のstat構造体の日付情報をprintf関数で 出力書式を"%d %d \n"のように連続して出力するとvisual Cだけ、 二つ目の変数が期待した通りに出力できないのでソースをいじって どのような状態で出力できないのか確認したところ、 Visual studio 2012,2013のvisual Cに於いては、 stat構造体の time_t型変数をprintf系関数で出力する場合、その変数以降に 続けて出力する他の変数が正常に出力できなくなることに 気づきました。これはなぜでしょう? 以下のC言語のソースの例では、先にstring変数を出力してstat構造体の time_t型変数を出力した場合(debug2)には問題ないのに、 変数の出力順を入れ替えるとVisual Cではtime_t型変数以降は 正常に出力できません。(debug3) 尚、time_t変数のst_mtime、st_ctime共、同様の結果になります。 printfの書式通りに出力されないだけで、変数の中身は壊れていません。 // 以下サンプルソース wsttes.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/stat.h> #ifdef _HPUX_SOURCE //HP-UXのansi-Cでもコンパイルできるように #define _stat stat #endif int main() { char s1[100]; // s1 struct _stat t1; // t1 strcpy(s1,"testA"); t1.st_atime=111111; // stat構造体を変数として利用しているだけ printf("debug0 s1=%s\n",s1); printf("debug1 t1=%d\n",t1.st_atime); printf("debug2 s1=%s t1=%d\n",s1,t1.st_atime); printf("debug3 t1=%d s1=%s\n",t1.st_atime,s1); return 0; } /*実行結果 Borland C(BCC32) d:\users\work\bc>wsttes debug0 s1=testA debug1 t1=111111 debug2 s1=testA t1=111111 debug3 t1=111111 s1=testA Visual C(visual studio 2012 or 2013) d:\users\work\vc>wsttes debug0 s1=testA debug1 t1=111111 debug2 s1=testA t1=111111 debug3 t1=111111 s1=(null)  ←ここだけ異常? HP-UX ansi-C hp-ux % wsttes debug0 s1=testA debug1 t1=111111 debug2 s1=testA t1=111111 debug3 t1=111111 s1=testA */

  • getaddrinf()で取得したIPアドレス表示

    お世話になります。 C言語でソケット通信の勉強中です。 CentOS6.4を使っています。 LIST1は、 IPアドレスではなくホスト名がコマンド引数で渡されたとき、 getaddrinfo()でIPアドレスを取得して、 sendto()でサーバにメッセージを送信するだけの、 クライアントのプログラムです。 このLIST1のudp通信自体は上手くいくのですが、 終わりの方で、 getaddrinfo()で取得したIPアドレスを inet_ntoa()を使って文字列表示しようとすると、 セグメンテーション違反です (コアダンプ)となってしまいます。 inet_ntoa()の引数が疑わしく、 いろいろ渡し方を変えたり、参照方法を変えたりしてみたのですが、、 なかなか解決しません。 ちゃんと、192.168.12.1とか表示するにはどうすれば良いでしょうか? ■LIST1 #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> int main(int argc,char *argv[]){ int sock; struct addrinfo hints,*res; int n; int err; if(argc != 2){ fprintf(stderr,"Usage : %s dst \n",argv[0]); return 1; } /* IP アドレス表記+ホスト名両方に対応 */ memset(&hints,0,sizeof(hints)); hints.ai_family = AF_UNSPEC; /* IPV4 IPV6 両方に対応 */ hints.ai_socktype = SOCK_DGRAM; err = getaddrinfo(argv[1],"12345",&hints,&res); if(err != 0){ perror("getaddrinfo"); printf("getaddrinfo %s\n",strerror(errno)); printf("getaddrinfo : %s \n",gai_strerror(err)); return 1; } sock = socket(res->ai_family,res->ai_socktype,0); if(sock < 0){ perror("socket"); return 1; } { const char *ipverstr; switch (res->ai_family){ case AF_INET: ipverstr = "IPv4"; break; case AF_INET6: ipverstr = "IPv6"; break; default: ipverstr = "unknown"; break; } printf("ipverstr = %s\n ",ipverstr); } n = sendto(sock,"HELLO",5,0,res->ai_addr,res->ai_addrlen); //n = sendto(sock,"HELLO", 5, 0,(struct sockaddr *)addr, sizeof(addr)); if(n<1){ perror("sendto"); { } return 1; } printf("############ finish !! #######\n"); close(sock); freeaddrinfo(res); struct sockaddr_in *addr; addr = (struct sockaddr_in *)res->ai_addr; printf("inet_ntoa(in_addr)sin = %s\n",inet_ntoa((struct in_addr)addr->sin_addr)); return 0; }

  • スレッドとメッセージキューに関して

    現在、下記のようなプログラムを作成しています。 内容は、メッセージキューを受信するスレッドを生成するというイメージです。 処理内容は下記のようになります。  (1)メッセージキューの生成  (2)スレッド生成(メッセージキュー受信側)  (3)スレッド停止  (4)メッセージキューの削除 しかし、(3)のスレッド停止を実施しても、(4)のメッセージキューの削除以降にて、msgrcvのエラーが出力されてしまいます。 スレッド停止を行ったことから、TestThreadは動作しなくなり、(4)のメッセージキューの削除にて、エラーともならずに終了することを望んでりますが、上手くいきません。 下記に作成しているプログラムを記載いたします。 正常終了をするには何がいけないのでしょうか? ご教授宜しくお願い致します。 [test.cc] ---------------------------------------------------------------- #include <time.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <ctype.h> #include <stdlib.h> #include <pthread.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/msg.h> // メソッドポインタ定義 typedef void (*testT); // スレッドID pthread_t threadId; // メッセージキュー識別子 int msqId; // 送受信するメッセージ struct msgbuf{ long int type; char data[BUFSIZ]; }; // テストスレッド void TestThread() { // メッセージ struct msgbuf message; while( 1 ) { printf("### TEST ###\n"); printf("msq start\n"); // 受信 if( msgrcv( msqId, &message, BUFSIZ, 0, 0 ) == -1) { printf("ERR! msgrcv errno[%d]\n", errno); continue; } printf("msq ed\n"); sleep(1); } return; } // メイン int main(int argc, char *argv[]) { // メッセージキュー識別子退避変数 int testMsqid; // スレッド操作リターン値 int status; // スレッドa用のパラメータ pthread_t thread_test; printf("### TEST START ###\n"); // メッセージキューの作成 if( (testMsqid = msgget((key_t)1111, 0666 | IPC_CREAT)) == -1 ) { printf("ERR! CREATE bkMsqId[%d]\n", testMsqid); return 1; } // メッセージキュー識別子を共通変数に設定 msqId = testMsqid; printf("msgget OK\n"); sleep(5); // スレッドを生成 status = pthread_create(&thread_test, NULL, (void*(*)(void*))TestThread, (void*)NULL); if(status!=0) { printf("pthread_create ng\n"); return 1; } printf("pthread_create OK\n"); sleep(5); // スレッド停止 status = pthread_cancel(thread_test); // スレッド停止結果 if ( status != 0 ) { printf("pthread_cancel ng\n"); return 1; } printf("pthread_cancel OK\n"); sleep(5); // メッセージキューの削除 if ( msgctl( msqId, IPC_RMID, NULL) == -1 ) { printf("msqId[%d] errno[%d]\n", msqId, errno); return 1; } printf("msgctl OK\n"); sleep(5); printf("### TEST E N D ###\n"); return 0; } ----------------------------------------------------------------

  • キャストの仕方(std::stringをconst char*へ)を教えてください。

    c++で作成したものをコンパイルしたところ、 下記のようなエラーメッセージが表示されました。 cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int stat(const char*, stat*) 自分の解釈では、 stat関数の第1引数がconst char*なのに、 プログラムの中では  #include <sys/types.h>  #include <sys/stat.h>  using namespace std;   :  string aaa;   :  struct stat st;  if(stat(aaa,&st)!=-1){・・・   : という感じで記述しているので、 型が変換できない という感じのことを言っているのかなぁ・・・? と思っているのですが、間違いですか? また、間違えていないとしたら・・・、 このstringで宣言しているaaaをchar*(?)にキャストする方法 と言いますか、このエラーを解決する方法を教えてください。 毎度のことですが、理解不十分で、質問の意味が通じにくいかも しれませんが、どうか宜しくお願いいたします。m(_ _)m

  • C言語で自作したcpコマンドが上手く動作しません

    当方、プログラミングを勉強中の学生です。 先日、ファイル入出力関数を用いてcpコマンドを自作しました。 一応、コンパイルは通るのですが、コピーしたファイルを開くことができません。 そのファイルのパーミッションを確認してみたところ 「----------」となっており、読み書き実行すべて不可となっていました。 ソースは以下の通りなのですが、何が問題でしょうか。 回答よろしくお願い致します。 #include<stdio.h> #include<fcntl.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #define SIZE 8192 int main(int argc, char *argv[]) { int fd1, fd2; char buf[SIZE]; if ( argc != 3 ){ char err_message[] = "ファイル名を指定して下さい。\n"; write(2, err_message, strlen(err_message)); return 1; } argv[0] = "mycopy"; fd1 = open(argv[1], O_RDONLY); fd2 = open(argv[2], O_WRONLY | O_CREAT); if (fd1 < 0 || fd2 < 0) { char err_message[] = "ファイルをオープンできません。"; write(2, err_message, strlen(err_message)); write(2, strerror(errno), strlen(strerror(errno))); write(2, "\n", 1); return 1; } while(1) { if (read(fd1, buf, SIZE) == 0) { break; } else if (read(fd1, buf, SIZE) > 0) { write(fd2, buf, SIZE); } else { char err_message[] = "エラーが発生しました。"; write(2, err_message, strlen(err_message)); write(2, strerror(errno), strlen(strerror(errno))); write(2, "\n", 1); return 1; } } close(fd1); close(fd2); return 0; }

  • fwrite処理について

    fwrite処理を行っているのですが、うまくファイルに出力されません。どこがおかしいか分からない次第です。 返答のほど、よろしくお願いします。 #include <stdio.h> #include <string.h> #include <stdlib.h> struct ll{ long int bango; char name[20]; char denwa[15]; }; FILE *fpbin; /*FILE構造体(グローバル変数)*/ struct ll *memalloc(void); void main(void) { struct ll *p; p = memalloc(); fpbin = fopen("bin","w+b"); printf("追加するNo 名前 tel >\n"); scanf("%ld %s %s", &p -> bango, p -> name, p -> denwa); printf("%ld %s %s\n", p -> bango, p -> name, p->denwa); fwrite(p,sizeof(struct ll),1,fpbin); fclose(fpbin); } struct ll *memalloc(void) { struct ll *p; if ( (p = (struct ll *)malloc(sizeof(struct ll))) != NULL ){ return p; } printf("メモリの動的割当に失敗しました。\n"); exit (1); return p; }

専門家に質問してみよう