1

私はこれを試しました:

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

1 に答える 1

4

書き込む文字列の実際の長さを取得するには、sizeof()を置き換える必要があります。strlen()例えば: write(out_fd, tmp,strlen(tmp));

于 2013-01-29T11:33:53.093 に答える