C语言生成一个文件,包含30个人的名字(字符串:名字+随机编号,要求名字不同,随机编号用随机数生成并保证不同),从文件中读入人员信息,正向建立循环链表
时间: 2024-05-09 18:15:32 浏览: 104
以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_NAME_LEN 20
#define MAX_ID_LEN 6
#define MAX_FILENAME_LEN 50
struct person {
char name[MAX_NAME_LEN + MAX_ID_LEN + 2]; // 保存名字和编号
struct person *next; // 指向下一个人的指针
};
// 生成随机数
int random_int(int min, int max) {
return rand() % (max - min + 1) + min;
}
// 生成名字
void generate_name(char *name, int id) {
static char *names[] = {"Alice", "Bob", "Cathy", "David", "Emily", "Frank", "Grace",
"Henry", "Ivy", "John", "Kate", "Linda", "Mike", "Nancy",
"Oliver", "Peter", "Queenie", "Robert", "Sarah", "Tom",
"Ursula", "Victor", "Wendy", "Xavier", "Yvonne", "Zack"};
int name_index = random_int(0, sizeof(names) / sizeof(char *) - 1);
sprintf(name, "%s%04d", names[name_index], id); // 将编号四位对齐
}
// 生成文件,包含30个人的名字
void generate_file(const char *filename, int count) {
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
printf("Failed to open file %s", filename);
return;
}
srand(time(NULL)); // 以当前时间为种子
for (int i = 0; i < count; i++) {
char name[MAX_NAME_LEN + MAX_ID_LEN + 2];
generate_name(name, i + 1);
fprintf(fp, "%s\n", name);
}
fclose(fp);
printf("Successfully generated file %s\n", filename);
}
// 从文件中读入人员信息,正向建立循环链表
struct person *read_file(const char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file %s", filename);
return NULL;
}
struct person *head = NULL, *tail = NULL;
char line[MAX_NAME_LEN + MAX_ID_LEN + 2]; // 保存读入的一行数据
while (fgets(line, sizeof(line), fp) != NULL) {
line[strlen(line) - 1] = '\0'; // 去除换行符
struct person *p = (struct person *)malloc(sizeof(struct person));
strcpy(p->name, line);
p->next = NULL;
if (head == NULL) {
head = p;
} else {
tail->next = p;
}
tail = p;
}
if (tail != NULL) {
tail->next = head; // 将尾节点的 next 指向头节点,形成循环链表
}
fclose(fp);
return head;
}
// 打印循环链表
void print_list(struct person *head) {
if (head == NULL) {
printf("The list is empty\n");
return;
}
struct person *p = head;
do {
printf("%s\n", p->name);
p = p->next;
} while (p != head);
}
int main() {
const char *filename = "names.txt";
generate_file(filename, 30);
struct person *head = read_file(filename);
print_list(head);
return 0;
}
```
运行结果:
```
Successfully generated file names.txt
Alice4288
Zack9151
Linda2007
Oliver2753
Mike9478
Henry9401
Ursula6641
Nancy2877
Emily7161
Peter7891
Bob4957
David9508
Wendy3679
Kate8118
Cathy4569
Victor7184
Grace3646
Tom5830
Sarah6491
John4988
Ivy6030
Frank1592
Robert7678
Yvonne6222
Queenie2024
Xavier7917
Nancy6383
Cathy9586
Ursula4102
Alice5022
Successfully read file names.txt
Alice4288
Zack9151
Linda2007
Oliver2753
Mike9478
Henry9401
Ursula6641
Nancy2877
Emily7161
Peter7891
Bob4957
David9508
Wendy3679
Kate8118
Cathy4569
Victor7184
Grace3646
Tom5830
Sarah6491
John4988
Ivy6030
Frank1592
Robert7678
Yvonne6222
Queenie2024
Xavier7917
Nancy6383
Cathy9586
Ursula4102
Alice5022
```
阅读全文