我正在尝试使用write()
打印出st->st_size
当我做这行的时候
write(fd, st->st_size, sizeof(st->st_size));
我收到以下错误。
`warning: passing argument 2 of ‘write’ makes pointer from integer without
a cast [-Wint-conversion]
write(fd, st->st_size, sizeof(st->st_size));`
`In file included from myls.c:4:0:
/usr/include/unistd.h:369:16: note: expected ‘const void *’ but argument is of type ‘__off_t {aka long int}’
extern ssize_t write (int __fd, const void *__buf, size_t __n) __wur;`
有什么办法可以解决这个问题吗?它对 stat
结构中的所有其他类似成员执行此操作
最佳答案
看第二个参数,st->st_size
。这是一个整数或长整型值。现在看一下write
的声明:
ssize_t write(int fd, const void *buf, size_t count);
write
期望变量的地址作为第二个参数,第三个参数是从该地址复制到文件描述符中的字节数。
这可能就是您想要的:
write(fd, &(st->st_size), sizeof(st->st_size));
以上代码会将 st_size
的二进制表示形式写入文件描述符。如果您想将该值写为文本,您可能应该考虑不同的方法来实现这一点。包括:
const size_t tmpbufsize = 50;
char tmp[tmpbufsize]; // big enough to hold a 64-bit int
snprint(tmp, tmpbufsize, "%ll", (long long)(st->st_size));
write(fd, tmp, strlen(tmp));
关于c - 使用 write() 打印 stat 结构时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57417511/