Reputation: 3707
I tried this:
#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;
}
but it writes some trash to my file:
is there any good way to write a number (float, int, double) to file using file descriptor and write? Thanks
thanks guys, solved:
#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;
}
Upvotes: 1
Views: 5505
Reputation: 1823
You need to replace sizeof()
with strlen()
to get the actual length of the string to write. e.g:
write(out_fd, tmp,strlen(tmp));
Upvotes: 4