如何用C程序根据学校条件从文本文件提取指定用户姓名
C程序实现筛选指定学校用户
以下是实现需求的C代码,能读取users.txt文件并筛选出所有来自「Legit Univ」的用户:
#include <stdio.h> #include <string.h> #define MAX_LINE_LEN 100 // 定义每行最大长度,可根据实际内容调整 int main() { FILE *file = fopen("users.txt", "r"); if (file == NULL) { printf("无法打开文件 users.txt\n"); return 1; } char line[MAX_LINE_LEN]; char name[MAX_LINE_LEN]; int count = 0; // 第一次遍历文件,统计符合条件的用户数量 while (fgets(line, MAX_LINE_LEN, file) != NULL) { // 定位每行中的逗号分隔符 char *comma_pos = strchr(line, ','); if (comma_pos == NULL) continue; // 跳过格式不符合的行 // 提取学校部分:跳过逗号后的空格,处理换行符 char *school = comma_pos + 2; char *newline = strchr(school, '\n'); if (newline != NULL) *newline = '\0'; // 判断是否为目标学校 if (strcmp(school, "Legit Univ") == 0) { count++; } } // 将文件指针重置到文件开头,准备第二次遍历输出内容 rewind(file); // 输出统计结果和符合条件的用户姓名 printf("Found %d users from Legit Univ\n\n", count); while (fgets(line, MAX_LINE_LEN, file) != NULL) { char *comma_pos = strchr(line, ','); if (comma_pos == NULL) continue; // 提取姓名部分:从行首到逗号前的内容 strncpy(name, line, comma_pos - line); name[comma_pos - line] = '\0'; char *school = comma_pos + 2; char *newline = strchr(school, '\n'); if (newline != NULL) *newline = '\0'; if (strcmp(school, "Legit Univ") == 0) { printf("%s\n", name); } } fclose(file); return 0; }
关键逻辑说明:
- 用
fopen打开文件,先判断是否打开成功,避免文件不存在或权限问题导致的错误。 - 两次遍历文件:第一次统计符合条件的用户数量,第二次输出对应的姓名;用
rewind重置文件指针实现重复读取。 - 用
strchr定位逗号分隔符,分别提取姓名和学校部分,处理换行符保证字符串比较的准确性。 - 用
strcmp直接对比学校字符串,确保筛选的准确性。
示例输出:
Found 2 users from Legit Univ John Paul James Lebron
内容的提问来源于stack exchange,提问作者Leet Rothschild
相关产品推荐
相关产品推荐

