txt如下:
ZQ112101
劉誠明
ZQ112102
劉磊
ZQ112103
劉義峥
ZQ112104
朱冠虞
ZQ112105
朱志陽
ZQ112106
樊穎卿
ZQ112107
劉玮
ZQ112108
朱美青
ZQ112109
朱翔
ZQ112110
朱信
ZQ112111
朱永樓
array[1] 希望能夠返回 ZQ112101
下邊提供的源碼供參考,linux試驗通過了,希望對你能有幫助。
//源碼文件 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
王五