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

时间:2013-04-01 16:09:15

标签: c unix file-io system-calls printf

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

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

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

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:4)

int foo;

write (fd, &foo, sizeof foo);

答案 2 :(得分:3)

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

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

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;
}