我试过这个:
#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)写入文件并写入?谢谢
谢谢大家,解决了:
#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/