6

如何使用 UNIX 的 write 系统调用将 int、float 或其他类型写入文件?我想这样做而不使用任何 lib 函数,如fprintfor fwrite

我想使用文件描述符而不是FILE*.

再次打开后,必须完全按照写入的方式读取文件,而无需知道要读取的大小。

4

3 回答 3

13

这很简单(请注意,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;
}
于 2013-04-01T16:24:10.577 回答
4
int foo;

write (fd, &foo, sizeof foo);
于 2013-04-01T16:24:26.390 回答
4

正如评论中确定的那样,问题更多是将数字转换为十进制数字而不是使用write调用。

要编写人类可读的 int 或 float,您必须将其转换为数字,然后写入该数字的字符。对于浮点数,如果内部表示使用与数字(例如十进制)不同的基数(例如二进制),那么这需要大量工作才能正确完成。我建议使用现有的开源代码或有关该主题的科学论文。

将 a转换int为十进制数字的代码相当简单:

#include <stdlib.h> //  For size_t.


/*  IntToString converts the int x to a decimal numeral, which is written to s.
    No terminal null character is written.  The number of characters written is
    returned.  s MUST point to space with enough room for the numeral,
    including a leading '-' if x is negative.
*/
size_t IntToString(char *s, int x)
{
    //  Set pointer to current position.
    char *p = s;

    //  Set t to absolute value of x.
    unsigned t = x;
    if (x < 0) t = -t;

    //  Write digits.
    do
    {
        *p++ = '0' + t % 10;
        t /= 10;
    } while (t);

    //  If x is negative, write sign.
    if (x < 0)
        *p++ = '-';

    //  Remember the return value, the number of characters written.
    size_t r = p-s;

    //  Since we wrote the characters in reverse order, reverse them.
    while (s < --p)
    {
        char t = *s;
        *s++ = *p;
        *p = t;
    }

    return r;
}


#include <stdio.h>  //  For printf.


//  Demonstrate IntToString.
static void Demonstrate(int x)
{
    char buf[100];
    size_t n = IntToString(buf, x);
    printf("IntToString(%d) = %.*s.\n", x, (int) n, buf);
}


#include <limits.h> //  For INT_MIN and INT_MAX.


int main(void)
{
    Demonstrate(0);
    Demonstrate(1);
    Demonstrate(9);
    Demonstrate(10);
    Demonstrate(INT_MAX-1);
    Demonstrate(INT_MAX);
    Demonstrate(-1);
    Demonstrate(-9);
    Demonstrate(-10);
    Demonstrate(INT_MIN+1);
    Demonstrate(INT_MIN);

    return 0;
}
于 2013-04-02T14:20:28.217 回答