printf格式化输出几点注记
生活随笔
收集整理的這篇文章主要介紹了
printf格式化输出几点注记
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
搞了很多年c/c++,有很多細小的東西,曾經不止一次遇到,可是一直都是放在零散的地方,要用的時候怎么也找不到,今天,我痛下決心,改掉不良習慣,把這些經驗或是tips記錄在這里,便于日后查找。
1.在統計網絡下載信息時,如何表達文件大小?
下面是輸出結果
2.打印size_t類型數據的長度,使用%lu。
下面是一個使用OpenSSL中HMAC-Sha1算法計算加密字符串的例子,記錄如下。
//gcc -g hmac_sha1_demo1.c -o hmac_sha1_demo1 -lcrypto --std=c99#include <stdio.h>
#include <string.h>
#include <openssl/hmac.h>int main()
{// The key to hashchar key[] = "012345678";// The data that we're going to hash using HMACchar data[] = "hello world";unsigned char* digest;// Using sha1 hash engine here.// You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etcdigest = HMAC(EVP_sha1(), key, strlen(key), (unsigned char*)data, strlen(data), NULL, NULL);printf("%s, len %lu\n", digest, strlen(digest));// Be careful of the length of string with the choosen hash engine. SHA1 produces a 20-byte hash value which rendered as 40 characters.// Change the length accordingly with your choosen hash enginechar mdString[41] = {'\0'};for(int i = 0; i < 20; i++)sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);printf("HMAC digest: %s\n", mdString);return 0;
}運行結果
3.打印time_t類型的數據,使用%lu,參見下面的小例子:時間字符串轉換為時間戳
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>time_t str2time(const char* s){struct tm tm_time;strptime(s, "%Y%m%d%H%M%S", &tm_time);time_t p = mktime(&tm_time);return p;
}int main(int argc, char* argv[]){const char* str = "20150622193125";time_t timep;timep = str2time(str);printf("%lu\n", timep);time(&timep);printf("%lu\n", timep);return 0;
}下面是運行結果:
總結
以上是生活随笔為你收集整理的printf格式化输出几点注记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: libcurl下载限速编程调研
- 下一篇: libcurl远程获取文件大小源码