Sam*_*Sam 4 c unix file-io printf system-calls
如何使用UNIX的write系统调用将int,float或其他类型写入文件?我想这样做,而不使用像fprintf或或任何lib函数fwrite.
我想使用文件描述符而不是FILE*.
再次打开后,必须完全按照写入的方式读取文件,而无需知道要读取的大小.
Jen*_*rer 10
这很简单(注意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;
}
Run Code Online (Sandbox Code Playgroud)