C語言寫檔案或日誌

來源:互聯網
上載者:User
/*功能:擷取當前系統時間傳回值:0-成功,-1-失敗out:儲存返回的系統時間,格式由fmt決定fmt:0-返回:yyyy-mm-dd hh24:mi:ss, 1-返回:yyyy-mm-dd, 2-返回:hh24:mi:ss*/int getTime(char *out, int fmt)// 擷取當前系統時間{if(out == NULL)return -1;time_t t;struct tm *tp;t = time(NULL);tp = localtime(&t);if(fmt == 0)sprintf(out, "%2.2d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d", tp->tm_year+1900, tp->tm_mon+1, tp->tm_mday, tp->tm_hour, tp->tm_min, tp->tm_sec);else if(fmt == 1)sprintf(out, "%2.2d-%2.2d-%2.2d", tp->tm_year+1900, tp->tm_mon+1, tp->tm_mday);else if(fmt == 2)sprintf(out, "%2.2d:%2.2d:%2.2d", tp->tm_hour, tp->tm_min, tp->tm_sec);return 0;}FILE* openFile(const char *fileName, const char *mode)// 開啟文字檔{FILE *fp = fopen(fileName, mode);return fp;}/*功能:將str寫入到檔案傳回值:寫檔案成功返回0,否則返回-1fp:檔案指標str:待寫入的字串bLog:1-是記錄檔,0-不是記錄檔說明:如果是記錄檔,將會在str前加上目前時間(格式如:2011-04-12 12:10:20)*/int writeFile(FILE *fp, const char *str, int bLog)// 寫字串到檔案,bLog表明是否為記錄檔{assert(fp != NULL && str != NULL);char curTime[100] = {0};int ret = -1;if(bLog) // 擷取當前系統時間{getTime(curTime, 0);ret = fprintf(fp, "[%s] %s\n", curTime, str);}elseret = fprintf(fp, "%s\n", str);if(ret >= 0){fflush(fp);return 0; // 寫檔案成功}elsereturn -1;}int closeFile(FILE *fp){return fclose(fp);}

需要的標頭檔有:

time.h, string.h, stdio.h, assert.h

在寫檔案的時候,一定要控制好開啟檔案時的mode,防止誤操作而刪除了原來檔案的內容。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.