【发布时间】:2016-07-19 17:54:36
【问题描述】:
#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 Details\n");
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 代码具有 Student 结构。我正在尝试从用户那里获取所有结构成员的值。内存分配给结构和两个成员 *name 和 *addr。当我尝试在文件 Student.txt 中使用 fwrite() 函数写入这些值时,它会在文件中显示像这样的随机输出( ཀའ㌱䔀8䵁ཀའ㈱䔀1䵁 ),它不是以可读的形式。请为我提供使用 fwrite() 函数在文件中写入结构成员的最佳方法。
【问题讨论】:
-
因为你写的是指针的值而不是它们包含的值。除非您将其更改为静态大小的分配(数组),否则您将无法以这种方式
fwrite该结构。 -
scanf("%s",&stu->clas);scanf("%s",&stu->age);你正在将字符串写入 int 容器,可能会损坏内存 -
@DavidHoelzer ,是否可以写出包含什么指针?我知道如果 *name 更改为 name[20] 并且 *addr 更改为 addr[20],我的代码将起作用。
-
在 C 中,当调用任何内存分配函数:(malloc, calloc, realloc) 时,返回值的类型为
void*,因此可以分配给任何指针。转换返回值只会使代码混乱,使其更难以理解、调试和维护。建议删除返回值的强制转换。注意:表达式:sizeof(char)在标准中被定义为 1,任何东西乘以 1 都没有效果,只会使代码混乱。建议删除表达式。 -
调用
fopen()时,打开追加,如果文件不存在,则创建文件,如果失败,打开写入+读取不会解决问题。
标签: c data-structures fwrite file-handling