如何使用write系统调用将int写入文件并完全按照写入方式读取它们?

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)

  • 我敢肯定,我们可以假设你至少忘记了系统调用`read`和`write`以便于阅读,我们不能吗?;-) (2认同)