ssize_t
-
头文件:
<sys/types.h>
-
有符号整型
-
格式符:
%zu
-
作用
- 字节数或(为负时)标识错误。
- 由多个系统调用和库函数返回,作为指示错误的一种方式。如read()、write()
ssize_t read(int fd, void *buf, size_t nbyte); ssize_t write(int fd, const char* buf, size_t nbyte);
-
POSIX手册原文
ssize_t : Used for a count of bytes or an error indication.
size_t
-
头文件:
<stddef.h>
-
无符号整型
-
格式符:
%zd
(这个似乎没有明确答案,stackoverflow上讨论的答案有%zd
、%jd
.但是也有用的是%ld
加long
强制类型转换(不过编译器也可以自动转换),毕竟:ssize_t
<=size_t
<=long
) -
作用
-
对象大小(以字节数计)。
用于表示内存中对象的大小,是sizeof
运算符和strlen
函数的返回值类型。这意味着它是无符号整型,它的具体大小取决于平台;选择的尺寸足够大以表示该平台上的所有尺寸。比如:对数组索引时,
size_t
保证足够大以表示数组中所有可能的索引。
-
-
POSIX手册原文(
man 7posix stddef.h
):
- size_t : Unsigned integer type of the result of the sizeof operator.
The implementation shall support one or more programming environments in which the
widths of ptrdiff_t, size_t, and wchar_t are no greater than the width of type long.
The names of these programming environments can be obtained using the confstr() func‐
tion or the getconf utility.
…- size_t : Used for sizes of objects.
size_t要点
- 是
sizeof()
运算符返回的类型。 - 无符号整型
- 足够大(取决于平台)
- 表示变量/存储空间大小
- 宽度不大于long类型
补充
之前一直有个疑惑:
关于read()
、write()
中一次性读写nbyte字节,nbyte的类型为size_t
。
返回值的类型却为ssize_t
,一次性读取的数量(nbyte)是可能超过ssize_t
的最大上限SSIZE_MAX
的,这个时候返回值无法根本表示不了那么多。
手册中:
- According to POSIX.1, if count is greater than SSIZE_MAX, the result is implementa‐tion-defined; see NOTES for the upper limit on Linux.
- If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-de‐
fined.
说是由具体实现定义的,不过很是奇怪它们怎么解决。
我想应该是没有解决的,不过看了stackoverflow上的讨论,觉得
很有道理:
SSIZE_MAX
,在我的64位机上,是2^63-1,也就是9223372036854775807,也就是8589934591.9GB,85亿GB。
呵呵,应该等到我去世都不用担心这个问题。