问题描述
- C 语言 按行读txt,存储到数组并查询
-
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] = '';
pstr = fgets(g_student_array[count].name, MAX_NAME_LEN, pFile);
if (!pstr)
{
goto l_error;
}
pstr[strlen(pstr)-1] = '';
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:%sn", g_student_array[i].ID, g_student_array[i].name);
rc = 1;
break;
}
}
if (i == g_count)
{
printf("don't find student with id %sn", id);
}
return rc;
}
void print_data()
{
int i;
printf("All Student Info:n");
for (i = 0; i < g_count; i++)
{
printf("id:%s name:%sn", 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
王五
解决方案二:
用ifstream的getline函数,要完整代码请先采纳。