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

标签 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);

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

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

    close(out_fd);
    return 0;
}

但它向我的文件写入了一些垃圾:

enter image description here

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

谢谢大家,解决了:

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

最佳答案

您需要将sizeof()替换为strlen()以获得要写入的字符串的实际长度。例如: write(out_fd, tmp,strlen(tmp));

关于c - 如何使用 C 中的文件描述符将数字(int,double)写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14581885/

相关文章:

linux - 如何在 Ruby on Rails 中监控打开的文件描述符?

C 循环移位 64 位无法正常工作

filesystems - inode 号和文件描述符有什么区别?

c - 来自 fread 的错误文件描述符

c++ - fopen 问题 - 打开的文件太多

c - 什么是正确的 fcntl 标志?

c - 如何解决 'undefined reference to pow'(已与 -lm 链接)?

c - 有没有办法在 C 中倒带标准输入?

C - fprintf 的奇怪行为

c - 在结构中使用什么级别的间接寻址?