vsnprintf列印可變參數的log

來源:互聯網
上載者:User

vsnprintf,C語言庫函數之一,屬於可變參數。用於向字串中列印資料、資料格式使用者自訂。

標頭檔:
#include <stdarg.h>
函式宣告:
int_vsnprintf(char*str,size_tsize,constchar*format,va_listap);
參數說明:
char *str [out],把產生的格式化的字串存放在這裡.
size_t size [in], str可接受的最大位元組數,防止產生數組越界.
const char *format [in], 指定輸出格式的字串,它決定了你需要提供的可變參數的類型、個數和順序。
va_list ap [in], va_list變數. va:variable-argument:可變參數
函數功能:將可變參數格式化輸出到一個字元數組。
用法類似於vsprintf,不過加了size的限制,防止了記憶體溢出(size為str所指的儲存空間的大小)。
傳回值:執行成功,返回寫入到字元數組str中的字元個數(不包含終止符),最大不超過size;執行失敗,返回負值,共置errno.[1] 
備忘:
linux環境下是:vsnprintf
VC6環境下是:_vsnprintf

---

#include <stdio.h>#include <stdlib.h>#include <stdarg.h>#include <string.h>static const int MAX_LOG_LENGTH = 4*1024;static void print_log(const char * format, ...){    va_list args;    va_start(args, format);    char buf[MAX_LOG_LENGTH];    vsnprintf(buf, MAX_LOG_LENGTH - 3, format, args);    strcat(buf, "\n");    fprintf(stdout, "log: %s", buf);    fflush(stdout);    va_end(args);}int main() {print_log("%d %s", 111000, "test");return 0;}

-------

參考:http://stackoverflow.com/questions/1056411/how-to-pass-variable-number-of-arguments-to-printf-sprintf

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.