在ID的数量中,否则它将带回null。欢迎任何帮助,甚至没有给我任何东西,只是编译错误。
struct client {
int id;
} cli[10]; // Let's say I already have cli.id = {1, 2, 3}
int idPosition(FILE *ptn1, int *arr, int idWanted, int i, int top);
int main() {
int id, position;
FILE *fp;
fp = fopen("clients.txt","rb+"); // I should have the cli.id = {1,2,3}
printf("ID: ");
scanf("%i", &id); // Let's suppose I insert a 3
position = idPosition(*fp, *cli, id, 0, 10); // I should get a 2, which would the position of the 3
}
int idPosition(FILE *ptn1, int *arr, int idWanted, int i, int top) {
fread(&arr[i],sizeof(arr[i]),1, ptn1); // ptn1 is pointing to FILE *fp which already fp = fopen("...","rb+");
if ((*(arr+i)).id == idWanted)
return i;
else if (idWanted == top)
return NULL;
return idPosition(ptn1, arr, idWanted, i+1, top);
}
我尝试了您的代码,实际上它不会编译。 该问题是在您的ID位置功能的参数集中。 即使ID结构仅保存整数,该函数也无法通过整数数组指针引用结构数组。 因此,我构建了一个简单的文件,该文件将ID保留为数字1-10,然后对您的代码进行了一些调整。 以下是调整代码的副本。
#include <stdio.h>
#include <stdlib.h>
struct client {
int id;
} cli[10];
int idPosition(FILE *ptn1, struct client *arr, int idWanted, int i, int top); /* The second parameter needed to reference the structure array even though it only holds an integer */
int main(void) {
int id, position;
FILE *fp;
fp = fopen("clients.txt","rb+"); // I should have the cli.id = {1,2,3}
printf("ID: ");
scanf("%i", &id); // Let's suppose I select a 3
position = idPosition(fp, cli, id, 0, 10); // I should get a 2, which would the position of the 3
printf("Position: %d\n", position);
}
int idPosition(FILE *ptn1, struct client *arr, int idWanted, int i, int top) {
fread(&arr[i],sizeof(arr[i]),1, ptn1); // ptn1 is pointing to FILE *fp which already fp = fopen("...","rb+");
if ((*(arr+i)).id == idWanted)
return i;
else
if (idWanted > top)
return NULL;
else
return idPosition(ptn1, arr, idWanted, i+1, top);
}
要指出的密钥位是“ ivposition”函数的参数列表。 第二个参数的定义不是“ int *arr”,而不是“ struct Client *arr”。 当函数最初称为时,这与传递“ CLI”数组的传递一致。
当我对此进行测试时,这是我在终端上的结果。
@Una:~/C_Programs/Console/Recursion/bin/Release$ hexdump clients.txt
0000000 0001 0000 0002 0000 0003 0000 0004 0000
0000010 0005 0000 0006 0000 0007 0000 0008 0000
0000020 0009 0000 000a 0000
0000028
@Una:~/C_Programs/Console/Recursion/bin/Release$ ./Recursion
ID: 3
Position: 2
第一个命令只是在“ client.txt”文件中介绍二进制数据。 然后,对该程序进行了呼叫,说明它在您的代码设计精神上发挥作用。