要求用C语言把文件id.txt中若干个人的姓名和身份证号码显示在屏幕上。然后,将其生日信息提取出来存放到一字符串中,并将所提取的姓名和生日信息写入另一个文件bd.txt。其中id.txt内容如下:张红 310110199609093420 王伟 310110199706151321 陶涛 220120199811086713
时间: 2023-06-26 09:07:45 浏览: 51
以下是实现代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LINE 100
int main() {
FILE *fp;
char line[MAX_LINE], name[20], id[20], birthday[9];
int i, j, len;
fp = fopen("id.txt", "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
while (fgets(line, MAX_LINE, fp) != NULL) {
len = strlen(line);
i = 0;
while (line[i] != ' ') {
name[i] = line[i];
i++;
}
name[i] = '\0';
i++;
j = 0;
while (i < len) {
id[j] = line[i];
i++;
j++;
}
id[j] = '\0';
// 提取生日信息
strncpy(birthday, id + 6, 8);
birthday[8] = '\0';
printf("%s %s\n", name, id);
// 写入bd.txt
FILE *fp2;
fp2 = fopen("bd.txt", "a");
fprintf(fp2, "%s 生日:%s\n", name, birthday);
fclose(fp2);
}
fclose(fp);
return 0;
}
```
程序先打开 id.txt 文件,然后逐行读取其中的内容。对于每一行,程序将字符串按照空格分割成姓名和身份证号码两部分,然后从身份证号码中提取生日信息,并将姓名和生日信息写入 bd.txt 文件。最后程序关闭文件并退出。
注意,程序中用到了字符串拷贝函数 strncpy(),可以避免越界访问和缺少字符串结束符的问题。