如何使用 UNIX 的 write 系统调用将 int、float 或其他类型写入文件?
我想这样做而不使用任何 lib 函数,例如fprintf
or fwrite
.
我想使用文件描述符而不是FILE*
.
再次打开后,文件必须完全按照写入的方式读取,而不需要知道读取的大小。
这很简单(请注意stdio.h
仅包含在printf
;没有它读/写工作):
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
// Open file with write permission (create if doesn't exist).
int fd = open("float.txt", O_CREAT | O_WRONLY);
float val = 1.5f;
if (fd != -1) {
write(fd, &val, sizeof(val));
close(fd);
}
// Test read.
fd = open("float.txt", O_RDONLY);
float new_val;
if (fd != -1) {
read(fd, &new_val, sizeof(new_val));
printf("new_val = %f\n", new_val);
close(fd);
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)