Chinaunix首页 | 论坛 | 博客
  • 博客访问: 398969
  • 博文数量: 75
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2015-06-03 18:24
文章分类

全部博文(75)

文章存档

2019年(1)

2018年(20)

2017年(14)

2016年(10)

2015年(30)

分类: LINUX

2017-12-28 22:20:09


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <time.h>
  7. #include <string.h>

  8. int Write_log_file(char *pFilename, char *pBuffer, int data_len)
  9. {
  10.     int ret_val = -1;
  11.     int fd = -1;
  12.     mode_t f_attrib;
  13.     time_t cur_time;
  14.     struct tm *pTm;
  15.     char date_buf[50];

  16.     f_attrib = S_IRWXU | S_IRWXG | S_IRWXO;
  17.     /**/
  18.     fd = open(pFilename, O_RDWR|O_APPEND|O_CREAT, f_attrib);
  19.     if(fd < 0)
  20.     {
  21.         printf("open Failed:%d\n", fd);
  22.         goto _OVER_;
  23.     }

  24.     /**/
  25.     time(&cur_time);
  26.     pTm = localtime(&cur_time);
  27.     snprintf(date_buf, 50, "[%04d-%02d-%02d %02d:%02d:%02d]",
  28.                     pTm->tm_year + 1900,
  29.                     pTm->tm_mon + 1,
  30.                     pTm->tm_mday,
  31.                     pTm->tm_hour,
  32.                     pTm->tm_min,
  33.                     pTm->tm_sec);
  34.     /**/
  35.     ret_val = write(fd, date_buf, strlen(date_buf));
  36.     if(ret_val != (int)strlen(date_buf))
  37.     {
  38.         printf("write Failed:%d\n", ret_val);
  39.         goto _OVER_;
  40.     }
  41.     
  42.     /**/
  43.     ret_val = write(fd, pBuffer, data_len);
  44.     if(ret_val != data_len)
  45.     {
  46.         printf("write Failed:%d\n", ret_val);
  47.         goto _OVER_;
  48.     }

  49. _OVER_:
  50.     if(fd >= 0)
  51.     {
  52.         close(fd);
  53.     }
  54.     return ret_val;
  55. }

  56. /**/
  57. int main(int argc, char **argv)
  58. {
  59.     int i;
  60.     char buffer[20];
  61.     
  62.     for(i = 0; i < 20; i++)
  63.     {
  64.         snprintf(buffer, 20, "hello%dhello\n", i);        
  65.         Write_log_file((char *)"./a.txt", (char *)buffer, strlen(buffer));
  66.     }

  67.     return 0;
  68. }

阅读(1144) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~