簡體   English   中英

如何從.txt文件中讀取文本,然后將其存儲在記錄(數據結構)中?

[英]How to read text from a .txt file and then store it in a record (data structure)?

我有一個.txt文件,每行結束:StudentID,firstName,lastName和score。 我想在C中編寫一個程序來讀取.txt文件並將每個學生的所有信息存儲在RECORD(數據結構)中。 問題是我不知道我必須使用的條件,以便分別閱讀每個不同的元素(StudentID,firstName等),因為它們只是分隔一個空格''然后還有我有的問題更改行以存儲下一個學生信息...任何幫助?

以下建議的代碼片段應足以指導您編寫應用程序。

要編譯/鏈接以下代碼,您將需要頭文件:

 #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數組中的實例

如果您需要更多幫助,請在此答案下方發布任何明確請求等作為評論

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM