【问题标题】:How to go at the beginning of a line with fseek()如何使用 fseek() 在行首
【发布时间】: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()

标签: c++ c file scanf fseek


【解决方案1】:

我会使用ftell 获取到每行开头的偏移量,然后用fgets 读取该行并用sscanf 解析该行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多