使用int read(struct person p[])函数读取数据文件的函数。其中数组 p 用于存放从文件person.txt中读取到的公民信息,函数返回读取到的公民信息记录数。
时间: 2024-03-22 11:41:30 浏览: 28
下面是一个示例代码,其中假设person.txt文件中每行包含姓名和年龄两个字段,用空格隔开:
```
#include <stdio.h>
struct person {
char name[20];
int age;
};
int read(struct person p[]) {
FILE *fp;
int count = 0;
fp = fopen("person.txt", "r");
if (fp == NULL) {
printf("Failed to open file person.txt\n");
return -1;
}
while (!feof(fp)) {
fscanf(fp, "%s %d", p[count].name, &p[count].age);
count++;
}
fclose(fp);
return count;
}
int main() {
struct person p[100];
int count = read(p);
printf("Read %d person records.\n", count);
return 0;
}
```
在该示例代码中,read函数使用fopen打开person.txt文件,并在while循环中使用fscanf读取文件中的每一行数据,将姓名和年龄分别存放到数组p[count].name和p[count].age中,然后将count计数器自增。最后返回count表示读取到的公民信息记录数。注意,在读取文件时应该判断文件是否存在或打开失败,以及在读取文件结束后应该关闭文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)