【发布时间】:2016-02-01 00:35:02
【问题描述】:
我有一个函数可以检查传递的参数是否在误差范围内与 .dat 文件中的参数匹配。
我想做的是找到最佳匹配。因此,我阅读了整个文件并跟踪给我最佳匹配的行。阅读完文件后,我想返回该特定行并将其作为最终结果阅读。
但是,我不能做那个“回去”的部分。
我的功能是:
int isObjectMatches(FILE *rPtr, struct objectDatabaseList *db, double area, double length)
{
double sum;
errno_t err;
double const errorThreshold = 0.4;
double minError = 100.0;
int lineNo = 0, bestMatchNo = 0;
bool match = false;
if ((err = fopen_s(&rPtr, "objects.dat", "r")) != 0)
printf("Couldn't open the file to read.\n");
else
{
rewind(rPtr);
while (fscanf_s(rPtr, "%14s%lf%lf", db->dName, sizeof db->dName, &db->dArea, &db->dLength) == 3)
{
lineNo++;
sum = pow((1 - (area / db->dArea)), 2) + pow((1 - (length / db->dLength)), 2);
if (sum > errorThreshold) // No possible match
{
continue; // Keep reading
}
else
if (sum < minError) // One possible match
{
minError = sum;
bestMatchNo = lineNo; // Take the line number
match = true;
continue; // Keep reading
}
}
if (match)
{
fseek(rPtr, (bestMatchNo - 1)*sizeof(struct objectDatabaseList), SEEK_SET); // Find the line
fscanf_s(rPtr, "%14s%lf%lf", db->dName, sizeof db->dName, &db->dArea, &db->dLength);
fclose(rPtr);
return 0;
}
}
fclose(rPtr);
return -1;
}
我的结构是:
struct objectDatabaseList
{
char dName[15];
double dArea;
double dLength;
};
请注意,一行的长度不是固定数字,因为“名称”可能不同。
【问题讨论】:
-
使用
fscanf_s(rPtr, "%14s%lf%lf", ...,代码失去了检测行的能力。使用fgets()。