C语言 如何使用 fwrite() 函数在文件中一次写入结构成员


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct student{
    char *name;
    char *addr;
    int age;
   int clas;
 }*stu;
 int main()
 {
    FILE *fp;
    int choice,another;
    size_t recsize;
    size_t length;
   struct student *stu=(struct student *)malloc(sizeof(struct student));
   stu->name=(char *) malloc(sizeof(char)*20);
   stu->addr=(char*)malloc(sizeof(char)*20);
   recsize=sizeof(*stu);

           fp=fopen("student.txt","a+");
            if(fp==NULL)
               {
                 fp=fopen("student.txt","w+");
                 if(fp==NULL)
                  {
                    printf("cannot open the file");
                    exit(1);
                  }  
                }
                do
                 {
                   fseek(fp,1,SEEK_END);
                   printf("Please Enter student Detailsn");
                   printf("Student Name: ");
                   scanf("%s",stu->name);
                    printf("Address: ");
                    scanf("%s",stu->addr);
                    printf("Class: ");
                    scanf("%s",&stu->clas);
                    printf("Age: ");
                    scanf("%s",&stu->age);                     
                    fwrite(stu,recsize,1,fp);
                    printf("Add another Enter 1 ?n");
                    scanf("%d",&another);
                   }while(another==1);
                  fclose(fp);
        free(stu);

   }

我有 C 格式的代码,它有一个结构学生。我正在尝试从用户那里获取所有结构成员值。内存分配给结构和两个成员 *name*addr。当我尝试在学生文件中使用 fwrite(( 函数写入这些值时.txt它会在文件中显示随机输出 ( ཀའビル䔀8䵁ཀའ(株(䃀1䵁 ( 像这样在文件中,它不是可读形式。请为我提供使用 fwrite(( 函数在文件中编写结构成员的最佳方法。

您需要

使用 %d 而不是 %s 才能int

printf("Class: ");
scanf("%s",&stu->clas);
printf("Age: ");
scanf("%s",&stu->age);

应该是

printf("Class: ");
scanf("%d",&stu->clas);
printf("Age: ");
scanf("%d",&stu->age);

正如@David Hoelzer在评论中指出的那样:你写的是指针的价值,而不是它们包含的内容,改变

struct student{
    char *name;
    char *addr;

struct student{
    char name[20];
    char addr[20];

并删除这些行:

stu->name=(char *) malloc(sizeof(char)*20);
stu->addr=(char*) malloc(sizeof(char)*20);

最新更新