开发者社区 问答 正文

C 语言 按行读txt,存储到数组并查询

txt如下:
ZQ112101
刘诚明
ZQ112102
刘磊
ZQ112103
刘义峥
ZQ112104
朱冠虞
ZQ112105
朱志阳
ZQ112106
樊颖卿
ZQ112107
刘玮
ZQ112108
朱美青
ZQ112109
朱翔
ZQ112110
朱信
ZQ112111
朱永楼
array[1] 希望能够返回 ZQ112101

展开
收起
a123456678 2016-03-23 10:06:03 2077 分享 版权
1 条回答
写回答
取消 提交回答
  • //源码文件 student_manage.c
    
    #include 
    #include 
    #include
    
    #define MAX_NAME_LEN 64
    #define MAX_ID_LEN 16
    #define MAX_STUDENT_NR 100
    
    typedef struct student 
    {
    char ID[MAX_ID_LEN];
    char name[MAX_NAME_LEN];
    } student_t;
    
    student_t g_student_array[MAX_STUDENT_NR];
    int g_count = 0;
    
    void read_data(char * filename)
    {
    FILE *pFile = NULL;
    char *pstr = NULL;
    int count = 0;
    int i = 0;
    
    pFile = fopen(filename, "r");
    if (!pFile)
    {
        perror("fopen");
        goto l_out;
    }
    
    do
    {
        pstr = fgets(g_student_array[count].ID, MAX_ID_LEN, pFile);
        if (!pstr)
        {
            goto l_error;
        }
        pstr[strlen(pstr)-1] = '\0';
    
        pstr = fgets(g_student_array[count].name, MAX_NAME_LEN, pFile);
        if (!pstr)
        {
            goto l_error;
        }
        pstr[strlen(pstr)-1] = '\0';
    
        count++;
    
    } while (count < MAX_STUDENT_NR);
    l_error:
    
    if (!feof(pFile))
    {
        perror("fgets");
    }
    
    g_count = count;
    
    fclose(pFile);
    l_out:
    return;
    
    }
    
    int find_student_by_id(char *id)
    {
    int i;
    int rc = 0;
    
    for (i = 0; i < g_count; i++)
    {
        if (! strcmp(g_student_array[i].ID, id))
        {
            printf("id:%s name:%s\n", g_student_array[i].ID, g_student_array[i].name);
            rc = 1;
            break;
        }
    }
    
    if (i == g_count)
    {
        printf("don't find student with id %s\n", id);
    }
    
    return rc;
    }
    void print_data()
    {
    int i;
    printf("All Student Info:\n");
    for (i = 0; i < g_count; i++)
    {
    printf("id:%s name:%s\n", g_student_array[i].ID, g_student_array[i].name);
    }
    }
    
    int main(int argc, char **argv)
    {
    char * filename = "name.txt";
    char * id = "Z0002";
    
    printf("------------------------------------------------\n");
    printf("Stage1, read data from file %s ...\n", filename);
    read_data("name.txt"); 
    printf("------------------------------------------------\n");
    printf("Stage2, print info ...\n");
    print_data();
    printf("------------------------------------------------\n");
    printf("Stage3, find studnent with id(%s)\n", id);
    find_student_by_id(id);
    }
    
    //示例文件 name.txt
    Z0001
    张三
    Z0002
    李四
    Z0003
    王五
    2019-07-17 19:10:22
    赞同 展开评论