编译的时候只会生成dat文件 ,但还没输入信息就返回了,不知道为什么。是我写的顺序不对吗? 我对文件的输入输出的理解是:
(1)打开或新建文件并检查(用fopen);
(2)输入内容(用scanf);
(3)将内容输入文件中(用fwrite);
(4)关闭文件(用fclose).
理解和编写哪有错误的帮忙指出以下,谢谢!
#include<stdio.h>
#include<stdlib.h>
#define SIZE 5
struct Student_type //定义文本内容格式
{
char name[10];
int num;
int age;
char addr[15];
}stud[SIZE];
FILE*fp;
void save() //给出命令:新建或输入一个文本
{
if ((fp = fopen("E:\\JOKer\\Desktop\\visual studio_Projects\\Projects\\输入读出文本.dat", "wb")) == NULL)
printf("cannot open file\n");
}
void scanf_stack() //输入要写入文本的内容
{
printf("Please enter data of students:\n");
for (int i = 0; i < SIZE; i++)
scanf("%s%d%d%s", stud[i].name, &stud[i].num, &stud[i].age, stud[i].addr);
}
void write_stack() //将输入的内容集成块并写入相应的地址
{
for (int i = 0; i < SIZE; i++)
if (fwrite(&stud[i], sizeof(struct Student_type), 1, fp) != 1)
printf("file write error\n");
fclose(fp);
}
/*=============================================*/
int main()
{
save();
scanf_stack;
write_stack();
return 0;
}