`read()` 使用什么 return 值?
What return value to use for `read()`?
我注意到有好几次检查 read()
的 return 值,它使用的类型是 int
,但检查 man 我注意到 read()
return 是 ssize_t
类型的值。 我知道 "in general" int 应该比 ssize_t 大,这就是我们不会出现错误的原因。但我的问题是: 是否有理由使用 int
而不是 ssize_t
? 使用 ssize_t
?
示例代码:
int x;
//ssiz_t x;
x = read(fd, &a, sizeof(a));
if (x == sizeof(a))
// all is fine
if (x == -1)
// Error while reading file
if (x == 0)
// Unexpected end of file
Shouldn't it be a best practice to use ssize_t
?
是的。
通常使用函数定义为 return 的任何类型。
int
is supposed to be bigger than ssize_t
不,总的来说不是,至少不是积极的部分。
The type ssize_t
shall be capable of storing values at least in the range [-1
, {SSIZE_MAX
}].
I got that "in general" int is supposed to be bigger than ssize_t and that's why we don't occur in a error.
事实并非如此。没有任何理由可以证明该假设是正确的。
is there a reason to use int instead of ssize_t? Shouldn't it be a best practice to use ssize_t?
是的。使用 ssize_t
存储 read()
的 return.
在您的大多数用例中,read()
可能正在处理可以由 int
处理的字节。因此,您可能从未在使用 int
时遇到过任何问题。但是,没有理由比 ssize_t
更喜欢 int
。始终使用正确的类型。
我注意到有好几次检查 read()
的 return 值,它使用的类型是 int
,但检查 man 我注意到 read()
return 是 ssize_t
类型的值。 我知道 "in general" int 应该比 ssize_t 大,这就是我们不会出现错误的原因。但我的问题是: 是否有理由使用 int
而不是 ssize_t
? 使用 ssize_t
?
示例代码:
int x;
//ssiz_t x;
x = read(fd, &a, sizeof(a));
if (x == sizeof(a))
// all is fine
if (x == -1)
// Error while reading file
if (x == 0)
// Unexpected end of file
Shouldn't it be a best practice to use
ssize_t
?
是的。
通常使用函数定义为 return 的任何类型。
int
is supposed to be bigger thanssize_t
不,总的来说不是,至少不是积极的部分。
The type
ssize_t
shall be capable of storing values at least in the range [-1
, {SSIZE_MAX
}].
I got that "in general" int is supposed to be bigger than ssize_t and that's why we don't occur in a error.
事实并非如此。没有任何理由可以证明该假设是正确的。
is there a reason to use int instead of ssize_t? Shouldn't it be a best practice to use ssize_t?
是的。使用 ssize_t
存储 read()
的 return.
在您的大多数用例中,read()
可能正在处理可以由 int
处理的字节。因此,您可能从未在使用 int
时遇到过任何问题。但是,没有理由比 ssize_t
更喜欢 int
。始终使用正确的类型。