本帖最后由 notfornothing 于 2019-6-16 20:22 编辑
你好,请教一个问题,不用fwrite,而是在文本文档.txt中输入,但是之后用fread读不出来.
这是正常的代码:#include <stdio.h>
#include <string.h>
#include <windows.h>
struct student
{
int number;
char name[20];
};
int main()
{
FILE *fp = NULL;
int size;
fp = fopen("data.txt", "w+");
struct student s[4] = {{11, "jack"}, {22, "lucy"}, {33, "come"}, {44, "zuse"}};
for (int i = 0; i < 4; i++)
size = fwrite(s + i, sizeof(struct student), 1, fp);
fclose(fp);
fp = fopen("data.txt", "r");
struct student stu[4];
for (int j = 0; j < 4; j++)
fread(stu + j, sizeof(struct student), 1, fp);
for (int k; k < 4; k++)
printf("%d %s \n", stu[k].number, stu[k].name);
system("pause");
}
下面是用fread读取手动输入到文本文档.txt中的内容的代码 但是我读取不出来
#include <stdio.h>
#include <string.h>
#include <windows.h>
struct student
{
int number;
char name[20];
};
int main()
{
FILE *fp = NULL;
fp = fopen("data.txt", "r");
struct student stu[4];
for (int j = 0; j < 4; j++)
fread(stu + j, sizeof(struct student), 1, fp);
for (int k; k < 4; k++)
printf("%d %s \n", stu[k].number, stu[k].name);
system("pause");
}
下面是txt文件文档11 jack
22 lucy
33 come
44 zuse
我问这个问题是因为老师要求说从文本文件中读出数据,但是那个数据又是结构体数据.
不知道怎么用fread读取 |