我正在尝试将结构数据类型的变量写入文件(config.dat)中,并用换行符分隔,即:
9001
00
128930
2
但我只能写不带空格:
9001001289302
这是代码:
int main()
{
typedef struct
{
char cp[4];
char id[2];
char correlative[6];
char digit[1];
} log;
FILE *fl;
log new_log;
fl = fopen("config.dat", "w");
printf ("\nCP: ");
gets (new_log.cp);
printf ("ID: ");
gets (new_log.id);
printf ("Correlative: ");
gets (new_log.correlative);
printf ("Digit");
gets (new_log.digit);
fwrite(&new_log, sizeof(log), 1, fl);
fclose(fl);
return 0;
}
我能做什么?谢谢!
最佳答案
这就是您真正需要的。
#include <stdio.h>
#include <stdlib.h>
int main()
{
typedef struct
{
char cp[1 + 1 + 4];
char id[1 + 1 + 2];
char correlative[1 + 1 + 6];
char digit[1 + 1 + 1];
} log;
/* I add `1' for the terminating null byte '\0', and another `1' for the `\n` new line */
FILE *fl;
log new_log;
fl = fopen("config.dat", "w");
if (fl == NULL)
return 1;
printf ("\nCP: ");
fgets (new_log.cp, sizeof(new_log.cp), stdin);
fprintf (fl, "%s", new_log.cp);
printf ("ID: ");
fgets (new_log.id, sizeof(new_log.id), stdin);
fprintf (fl, "%s", new_log.id);
printf ("Correlative: ");
fgets (new_log.correlative, sizeof(new_log.correlative), stdin);
fprintf (fl, "%s", new_log.correlative);
printf ("Digit: ");
fgets (new_log.digit, sizeof(new_log.digit), stdin);
fprintf (fl, "%s", new_log.digit);
fclose(fl);
return 0;
}
请注意,我使用了 fgets
来避免缓冲区溢出。
关于C - 在换行符中写入纯文本文件结构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27461361/