programing

C write는 분명히 숫자를 쓰지 않는다.

yoursource 2022. 12. 11. 10:40
반응형

C write는 분명히 숫자를 쓰지 않는다.

구조체를 .txt 파일에 쓰려고 하는데fwrite가 예상대로 동작하지 않는 것 같습니다.나는 그 파일을 기대했다.file.txt나타내다Jhonny 18 10.0하지만 그렇지 않아, 내가 뭘 놓쳤나?

제 코드는 다음과 같습니다.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "file.txt"

typedef struct {
    char name[32];
    int age;
    float value;
} Test_struct;

int main(int argc, char** argv)
{
    Test_struct test;
    strcpy(test.name, "Jhonny");
    test.age = 18;
    test.value = 10.0;

    FILE* file = fopen(FILENAME, "w");
    if (file == NULL)
    {
        fprintf(stderr, "\nAn error occurred while opening the file\n");
        return -1;
    }

    if (fwrite(&test, sizeof(test), 1, file) < 0)
        return -1;

    fclose(file);

    return 0;
}

다음은 그 결과 파일입니다.

는 이 튜토리얼을 따랐다.

알고 보니fwrite()(.txt 파일에 쓰는 것은) 내가 원하는 기능을 하는 것이 아니다. 그래서 WhozCraig는 나에게 사용하라고 제안했다.fprintf()대신, 그게 결과 코드입니다.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "file.txt"

typedef struct {
    char name[32];
    int age;
    float value;
} Test_struct;

int main(int argc, char** argv)
{
    Test_struct test;
    strcpy(test.name, "Jhonny");
    test.name[7] = '\0';
    test.age = 18;
    test.value = 10.0;

    FILE* file = fopen(FILENAME, "w");
    if (file == NULL)
    {
        fprintf(stderr, "\nAn error occurred while opening the file\n");
        return -1;
    }

    if (fprintf(file, "%s %d %3.2f", test.name, test.age, test.value) < 0)
        return -1;

    fclose(file);

    return 0;
}

결과:

언급URL : https://stackoverflow.com/questions/73593855/c-fwrite-appearently-doesnt-write-numbers

반응형