strlcpy 有長度的copy 不是標準C 慎用

來源:互聯網
上載者:User

strlcpy

// Copy src to string dst of size siz. At most siz-1 characters
// will be copied. Always NUL terminates (unless siz == 0).
// Returns strlen(src); if retval >= siz, truncation occurred.
size_t
strlcpy(char *dst, const char *src, size_t siz);

而使用 strlcpy,就不需要我們去手動負責\0了,僅需要把 sizeof(dst) 告之 strlcpy 即可:

strlcpy(path, src, sizeof(path));
len = strlen(path);

if ( len >= sizeof(path) )
       printf("src is truncated.");

並且 strlcpy 傳回的是 strlen(str),因此我們也很方便的可以判斷資料是否被截斷。

[* 一點點曆史 *]

strlcpy 並不屬於 ANSI C,至今也還不是標準。

strlcpy 來源於 OpenBSD 2.4,之後很多 unix-like 系統的 libc 中都加入了 strlcpy 函數,在 FreeBSD、Linux 裡面都找到了 strlcpy。(Linux使用的是 glibc,glibc裡面有 strlcpy,則所有的 Linux 版本也都應該有 strlcpy)

但 Windows 下是沒有 strlcpy 的,對應的是strcpy_s函數

相關文章

聯繫我們

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