fseek() ile belli bir satıra gitmek

Başlatan vitruvius, 31 Ekim 2015, 23:54:04

vitruvius

Merhaba,

Bir fonksiyonla bir .dat dosyasına ulaşıp oradaki verilerle fonksiyona aktardığım verileri kıyaslıyorum. Yapmaya çalıştığım şey en uygun eşleşmeyi bulmak. Bunun için dosyanın tamamını okuyorum bu süreçte en iyi eşleşmenin yerini tespit ediyorum. Dosya okuma işlemi bitince o satıra dönüp son kez okuyup sonucu almak istiyorum.

Bu tekrar geri dönme işini yapamadım.

Fonksiyon şu şekilde:
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 da şu şekilde:
struct objectDatabaseList
{
    char dName[15];
    double dArea;
    double dLength;
};

vitruvius

Bu işi önce ftell() ile satırın pozisyonunu bulup, sonra fgets() ile satırı okuyup, sscanf_s ile de parse edip çözdüm.