检查int read(struct person p[]) { FILE *fp; int count=0; fp=fopen("person.txt",'r'); if(fp==NULL){ printf("Failed to open file.\n"); return 0; } while(fscanf(fp,"%s%s",p[count].ID,p[count].name==2){ count++; } fclose(fp); return count; }
时间: 2023-06-24 08:08:45 浏览: 34
在你的代码中,有一些问题:
1. `fopen` 函数的第二个参数应该是一个字符串,而你传递的是一个字符常量,应该使用双引号,而不是单引号。
2. `fscanf` 函数的第二个参数有误,你的意图是使用等于号将两个字符串的读取结果赋值给结构体中的两个成员变量,但是这是错误的语法。你应该使用逗号将多个参数分隔开,例如 `fscanf(fp, "%s %s", p[count].ID, p[count].name)`。
下面是修改后的代码:
```
int read(struct person p[]) {
FILE *fp;
int count = 0;
fp = fopen("person.txt", "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return 0;
}
while (fscanf(fp, "%s %s", p[count].ID, p[count].name) == 2) {
count++;
}
fclose(fp);
return count;
}
```
另外,你可能需要检查 `person.txt` 文件是否存在,并且文件中每行的格式是否正确,以免导致程序出现意外错误。
相关问题
用int read(struct person p[])读取数据文件的
好的,这是一个关于结构体数组的问题。假设我们有一个名为person的结构体,它包含三个成员:name、age和gender。现在我们有一个存储person数据的文件,我们想要从文件中读取数据,并将数据存储到一个person类型的数组中。
那么,我们可以使用如下的代码来实现:
```c
#include <stdio.h>
struct person {
char name[20];
int age;
char gender;
};
int read(struct person p[]) {
int i = 0;
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("打开文件失败!\n");
return 0;
}
while (!feof(fp)) {
fscanf(fp, "%s %d %c", p[i].name, &p[i].age, &p[i].gender);
i++;
}
fclose(fp);
return i;
}
int main() {
struct person p[100];
int count = read(p);
for (int i = 0; i < count; i++) {
printf("%s %d %c\n", p[i].name, p[i].age, p[i].gender);
}
return 0;
}
```
在上面的代码中,我们定义了一个名为person的结构体,然后定义了一个名为read的函数,该函数接受一个person类型的数组作为参数。在函数中,我们首先打开数据文件,并检查文件是否打开成功。然后,在一个while循环中,我们使用fscanf函数从文件中读取一个person的数据,然后将其存储到数组中,并将数组下标加1。最后,我们关闭文件并返回数组中存储的数据的数量。
在主函数中,我们定义了一个person类型的数组,然后调用read函数将数据读取到数组中。最后,我们使用循环遍历数组,并将每个person的数据打印到控制台上。
希望这能够帮助你解决问题。
使用int read(struct person p[])函数读取数据文件的函数。其中数组 p 用于存放从文件person.txt中读取到的公民信息,函数返回读取到的公民信息记录数。
下面是一个示例代码,其中假设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表示读取到的公民信息记录数。注意,在读取文件时应该判断文件是否存在或打开失败,以及在读取文件结束后应该关闭文件。