[英]C fwrite appearently doesn't write numbers
我正在尝试将结构写入 a.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()
不是正确的 function 做我想做的事(写入 a.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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.