반응형
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
반응형
'programing' 카테고리의 다른 글
문자열을 n자 세그먼트로 분할하려면 어떻게 해야 합니까? (0) | 2022.12.11 |
---|---|
크기 자동 조정을 사용하여 텍스트 영역 작성 (0) | 2022.12.11 |
에러 코드 1292 - 잘린 DUBLE 값 - Mysql (0) | 2022.12.11 |
JUnit 테스트 주석을 사용하여 예외 메시지를 강조하려면 어떻게 해야 합니까? (0) | 2022.12.11 |
하위 구성 요소의 VueJs 호출 메서드 (0) | 2022.12.11 |