2011-06-13 73 views
-1

如何將文件中的數據讀取到結構中? 我有這樣從文件中讀取數據

struct data 
{ 
    char name[20]; 
    int age; 
}; 

在文件student_info.txt的結構我有

ravi 12 raghu 14 datta 13 sujay 10 rajesh 13 

等與年齡等其他名稱。我怎樣才能從文件讀取結構數據?

讀這個名字和年齡應該是一個循環,即我第一次閱讀'ravi'和'12',那麼我應該將這些數據打包在結構中,並且只要結構設置。它應該回到文件,並閱讀'raghu'和'14'再次用這個數據打包結構,這應該是一個循環,直到我讀取文件中的所有數據

任何人都可以請告訴如何執行邏輯?

+3

功課?....... – 2011-06-13 06:00:02

+1

幸運的是,你可以使用'scanf()的'這一點,只要你細心限制名字讀至19個字符(留下一個用於長度null在字符串的末尾),並檢查來自'scanf()'的返回狀態。 – 2011-06-13 06:20:38

+0

由於您的程序是從文件輸入的,因此您可能需要使用'fscanf'。 – 2011-06-13 21:37:38

回答

0

你只需要從這個文件中讀取數據並根據一些標準分割該字符串。由於您的文件格式不正確,您將難以解析數據。

在您當前的場景中,您的文件只包含名字和數字,您可以通過檢測字符串中的空格字符來輕鬆解析該數字。但是如果你的任何名字包含空格,這可能會導致問題。

首先用一些字符分隔每一對單詞,如:或;或者製表符或換行符。 然後在每個分隔的字符串之間按空格分隔,然後讀取char數組中的所有文件內容,然後從該數組中嘗試查找指示一條記錄的特殊字符。 分開在不同的字符數組的每個記錄然後爲每個生成的陣再次,然後把它分解基於空間char和負載在你的結構

這只是爲了說明,原有的實現可能是不同的,

Student std = {first string, second integer}; 

希望該文件解決您的問題http://www.softwareprojects.com/resources//t-1636goto.html

+0

@DumbCode:如果存儲在文件中的數據運行到幾個K字節,該怎麼辦?我們需要分配一個大小的數組,在這段代碼中,我只給出了5個年齡相應的名字,如果我有1000個名字和千年的年齡那麼該怎麼辦? – raghavan 2011-06-13 06:22:54

+0

或者他可以像Jonathan Leffler所建議的那樣做,並且使用帶'%s'和'%d'說明符的'scanf'。這根本不是「困難的」。 – Marlon 2011-06-13 06:27:48

+0

看到它取決於您的要求。如果您想要閱讀的數據量較大,而不是完整閱讀,則需要優化閱讀。閱讀本文件希望能夠解決您的問題 http://www.softwareprojects.com/resources//t-1636goto.html – 2011-06-13 06:31:13

1

的方法是:

  1. 創建一個實例文件訪問的文件指針和計數器變量
  2. 使用文件指針打開文件流 - 檢查它是否已成功打開。如果fopen()失敗,文件指針將指向NULL
  3. 使用循環將數據讀入結構數組。 fscanf()函數返回的成功「匹配」的數量與它的格式字符串 - 這將是2(用這個循環條件)
  4. 關閉文件

代碼的一個例子:

#include <stdio.h> 

#define FILENAME "student_info.txt" 
#define MAX_NO_RECORDS 50 

struct data 
{ 
char name[20]; 
int age; 
}; 

int main(void) 
{ 
    /* Declare an array of structs to hold information */ 
    struct data StudentInfo[MAX_NO_RECORDS]; 
    /* Declare a file pointer to access file */ 
    FILE *s_info; 
    int student_no = 0; /* holds no. of student records loaded */ 

    /* open the file for reading */ 
    s_info = fopen(FILENAME, "r"); 
    /* Check if an error has occured - exit if so */ 
    if(s_info == NULL) 
    { 
     printf("File %s could not be found or opened - Exiting...\n", FILENAME); 
     return -1; 
    } 

    printf("Loading data...\n"); 
    while(fscanf(s_info, "%19s %i", StudentInfo[student_no].name, &StudentInfo[student_no].age) == 2) 
    { 
     /* refer to records with index no. (0 to (1 - no. of records)) 
      individual members of structure can be accessed with . operator */ 
     printf("%i\t%-19s %3i\n", student_no, StudentInfo[student_no].name, StudentInfo[student_no].age); 
     student_no++; 
    } 
    /* after the loop, student_no holds no of records */ 
    printf("Total no. of records = %i\n", student_no); 
    /* Close the file stream after you've finished with it */ 
    fclose(s_info); 

    return 0; 
}