【C语言】一个这样的文件怎么读入?

来源:百度知道 编辑:UC知道 时间:2024/05/10 01:13:40
001 John Book1 Q123
Book2 Z234
002 Mike Book3 R345
Book4 F789
Book5 J567
003 Mary Book6 Y876
文件名:stu_record.txt
数据依次为:学生号,姓名,该生所借书的书名,书号。每个人所借书的数量不定,最多为20本。学生数也不定,需要统计出学生数。
请问这样一个文件怎么读入呢,用fscanf函数~
主要是不知道结构体数组套结构体数组要怎么读,麻烦大家指教~
谢!

这么写就好了,n+1就是学生数。

#include <stdio.h>
#include <string.h>

struct student
{
char num[ 10 ], name[ 20 ];
char book[ 20 ][ 20 ], booknum[ 20 ][ 10 ];
int books;
};
int main( )
{
FILE* inp = fopen("stu_record.txt", "rt");
student stu[ 100 ];
char tmp[ 20 ];
int n = -1, m;
while ( fscanf( inp, "%s", tmp ) != EOF )
{
if ( tmp[ 0 ] >= '0' && tmp[ 0 ] <= '9' )
{
if ( n != -1 )
stu[ n ].books = m;
n++;
m = 0;
strcpy( stu[ n ].num, tmp );
fscanf( inp, "%s", stu[ n ].name );
fscanf( inp, "%s", stu[ n ].book[ m ] );
fscanf( inp, "%s", stu[ n ].booknum[ m ] );
}
else
{
m++;
strcpy( stu[ n ].book[ m ], tmp );
fscanf( inp, "%s", stu[ n ].booknum[ m ] );
}
}