Katie
Katie

Reputation: 3707

How to write a number (int, double) to file using file descriptor in C?

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:

enter image description here

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

Answers (1)

Tomer Arazy
Tomer Arazy

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

Related Questions