如何从.txt文件中读取文本,然后将其存储在记录(数据结构)中?

问题描述 投票:0回答:1

我有一个.txt文件,每行结束:StudentID,firstName,lastName和score。我想在C中编写一个程序来读取.txt文件并将每个学生的所有信息存储在RECORD(数据结构)中。问题是我不知道我必须使用的条件,以便分别阅读每个不同的元素(StudentID,firstName等),因为它们只是分隔一个空格''然后还有我有的问题更改行以存储下一个学生信息...任何帮助?

c data-structures
1个回答
0
投票

以下建议的代码片段应足以指导您编写应用程序。

要编译/链接以下代码,您将需要头文件:

 #include <stdio.h>  // fgets(), fopen(), fclose(), perror()
 #include <stdlib.h> // exit(), EXIT_FAILURE, strtof()
 #include <string.h> // strtok(), strcpy(), strtol()

关于;

 StudentID , firstName, lastName and score.

所以每个学生有4个字段输入。

每个领域有多长?

使用合理的尺寸猜测:

 StudentID is unsigned long integer 
 FirstName is char array, max 30 characters
 LastName  is char array, max 30 characters
 Score     is float

因此,持有一名学生的结构将是:

 struct student
 {
    size_t   StudentID;
    char     FirstName[30];
    char     LastName[30];
    float    Score;
 };

假设输入文件是文本行,那么读取一行

 // open the file for reading
 if( !(fp = fopen( "studentFile.txt", "r" ) ) )
 {
     perror( "fopen for student input file failed" );
     exit( EXIT_FAILURE );
 }


 struct student *students = NULL;
 size_t studentCount = 0;

 char buffer[128];
 while( fgets( buffer, sizeof( buffer ), fp ) ) 
 { 

然后必须将每一行分解为相关字段并放入结构的实例中

     // increase number of students in array by 1
     struct student * temp = realloc( students, (studentCount+1) * sizeof( struct student ) );
     if( !temp )
     {
         perror( "realloc for new student data failed:" )
         free( students );
         exit( EXIT_FAILURE );
     }

     students = temp;

     char *token = strtok( buffer, " ");
     if( token )
     {
         students[ studentCount ]->StudentID = (size_t)strtol( token, 10 );

         if( (token = strtok( NULL, " " ) )
         {
             strncpy( students[ studentCount ]->FirstName, token. sizeof( student.FirstName) )l

             if( (token = strtok( NULL, " " ) )
             {
                 strncpy( students[ studentCount ]->LastName, token, sizeof( student.LastName );

                 if( (token = strtok( NULL, " " ) )
                 {
                     students[ studentCount ]->Score = strtof( token, NULL ); 
                 }
             }
         }
     }
     studentCount++;
 }

然后,输入文件中的所有学生信息行现在都是struct student数组中的实例

如果您需要更多帮助,请在此答案下方发布任何明确请求等作为评论

© www.soinside.com 2019 - 2024. All rights reserved.