samedi 31 octobre 2015

How to go at the beginning of a line with fseek()

I have a function where I check if the passed arguments match with the ones in a .dat file within an error margin.

What I would like to do is find the best match. So, I read the whole file and keep track of the line which gives me the best match. After I am done with reading the file I would like to go back that specific line and read it as my final result.

But, I could not do that "going back" part.

My function is:

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;
}

And my struct is:

struct objectDatabaseList
{
    char dName[15];
    double dArea;
    double dLength;
};

Please note that the length of a line is not a fixed number as the "name" could be different.

Aucun commentaire:

Enregistrer un commentaire