VB程序设计教程(第四版)龚沛曾-实验8-6

实验8-6

VB程序题:编写一个随机文件程序。
要求:
(1)建立一个具有5个学生的学号、姓名和成绩的随机文件(Random. dat)。
(2)读出Random.dat文件中的内容,然后按成绩排序,最后按顺序写入另一个随机文件(Randoml.dat)。
(3)再一次读出文件的内容,按文件中的顺序将学生的信息显示在屏幕上,检查正确性。

解题,画3个按钮控件,代码如下:

Private Type Studtype
    no As String * 4
    name As String * 6
    mark As Single
End Type
Dim Student As Studtype, Stud(1 To 5) As Studtype, t As Studtype

Private Sub Command1_Click()
    Open "C:\Random.dat" For Random As #1 Len = Len(Student)
    With Student
        .no = "0001"
        .name = "张三"
        .mark = 66
    End With
    Put #1, 1, Student

    With Student
        .no = "0002"
        .name = "李四"
        .mark = 99
    End With
    Put #1, 2, Student

    With Student
        .no = "0003"
        .name = "王五"
        .mark = 88
    End With
    Put #1, 3, Student

    With Student
        .no = "0004"
        .name = "赵六"
        .mark = 55
    End With
    Put #1, 4, Student

    With Student
        .no = "0005"
        .name = "钱七"
        .mark = 77
    End With
    Put #1, 5, Student

    Close #1
End Sub

Private Sub Command2_Click()

扫描二维码关注公众号,回复: 6160770 查看本文章

    Open "C:\Random.dat" For Random As #1 Len = Len(Student) 
Print
Print "Random.dat 文件内容:"
    For i = 1 To 5
        Get #1, i, Student
        Print Student.no, Student.name, Student.mark
        Stud(i) = Student
    Next i
    Close #1

    For i = 1 To 5
        For j = i + 1 To 5
            If Stud(i).mark > Stud(j).mark Then t = Stud(i): Stud(i) = Stud(j): Stud(j) = t '按成绩排序
        Next j
    Next i

    Open "C:\Random1.dat" For Random As #2 Len = Len(Student)

    For i = 1 To 5
        Put #2, i, Stud(i)
    Next i

    Close #1
End Sub

Private Sub Command3_Click()
    Open "C:\Random1.dat" For Random As #1 Len = Len(Student)

Print
Print "Random1.dat 文件内容:"
    For i = 1 To 5
        Get #1, i, Student
        Print Student.no, Student.name, Student.mark
        Stud(i) = Student
    Next i
    Close #1
End Sub

猜你喜欢

转载自blog.csdn.net/xcxgood/article/details/89946017