C - 在换行符中写入纯文本文件结构变量

标签 c file struct newline

我正在尝试将结构数据类型的变量写入文件(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/

相关文章:

c++ - 指针数组分配的段错误?

c - 在用 C 实现的链表中使用单指针和双指针

c - (C) 使用 feof 时出现奇怪的崩溃

string - 在 Haskell 中解析输入文件文件

java - 分析文本文件

c++ - 如何使用方法返回指向对象结构的指针?

python - 使用 cython 比 struct.pack 更快

c - strcpy在汇编中是什么意思?

c# - 我应该如何为互操作声明这个 C 结构?

c - pthreads - 加入一组线程,等待一个线程退出