如何在C中使用文件描述符将数字(int,double)写入文件?

如何在C中使用文件描述符将数字(int,double)写入文件?,c,file-descriptor,C,File Descriptor,我试过这个: #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char **argv) { int out_fd = open("file.txt", O_WRONLY | O_CREAT, 0666); int i; scanf("%d", &i); cha

我试过这个:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int out_fd = open("file.txt", O_WRONLY | O_CREAT, 0666);

    int i;
    scanf("%d", &i);

    char tmp[12]={0x0};
    sprintf(tmp,"%11d", i);

    write(out_fd, tmp, sizeof(tmp));

    close(out_fd);
    return 0;
}
但它会将一些垃圾写入我的文件:

有没有什么好方法可以使用文件描述符将数字float、int、double写入文件并写入?谢谢

谢谢各位,解决了:

您需要用strlen替换sizeof,以获得要写入的字符串的实际长度。例如: 注销fd、tmp、strlentmp

您需要用strlen替换sizeof,以获得要写入的字符串的实际长度。例如: 注销fd、tmp、strlentmp

sizeoftmp返回12,但不是11。这就是为什么文件中会出现空字符。sizeoftmp返回12,而不是11。这就是为什么文件中会出现空字符。
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int out_fd = open("plik.txt", O_WRONLY | O_CREAT, 0666);

    int i;
    scanf("%d", &i);

    char tmp[1]={0x0};
    sprintf(tmp,"%d", i);

    write(out_fd, tmp, strlen(tmp));

    close(out_fd);
    return 0;
}