如何使用 fwrite 将结构的字符串成员写入文件?

How to write string member of structure to file using fwrite?

我在 c 中有一个代码,我正在使用包含 name 的结构来使用 scanf() 函数获取用户输入。每当我尝试使用 fwrite() 在文件中写入名称时,它不会写入我输入的所有字符,而只会写入几个字符(只有四个字符)。我知道问题出在 fwrite() 函数的 sizeof() 但我不知道应该在 sizeof() 里面写什么所以我可以存储我从用户那里得到的字符串。我知道如果使用 char name[20] 而不是 char *name.

它会起作用
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

struct Emp
{
  char *name;
  char *addr;
}*e;

int main()
{
   FILE *fp;

   e=(struct Emp *)malloc(sizeof(struct Emp));
   e->name=(char *)malloc(sizeof(char )*20);

   fp=fopen("Employee.txt","r+");
   if(fp==NULL)
   {
      fp=fopen("Employee.txt","w+");
      if(fp==NULL)
      {
        printf("cannot open the file");
        exit(1);
      }
    }

      printf("Name of Employee: ");
      scanf("%s",e->name);       
      fwrite(e->name,sizeof(e->name),1,fp);


return 0;
}

如果我输入员工姓名:chiranjibi fwrite()函数只会在文件中写入chir。有什么方法可以使此代码正常工作,以便我可以从用户输入任意数量的字符?

你可以直接给4作为第二个参数给fwrite()调用。

fwrite(e->name,4,1,fp);

因此,它只将前四个字符写入文件。如果您想根据用户输入进行更改,请声明一个变量并从用户那里获取要打印的字符数,然后将该变量作为第二个参数传递给此函数调用。

sizeof(e->name) returns 指针的大小(通常为 4 或 8)

使用strlen(e->name)获取字符串的长度。假设字符串以 null 终止。