gpt4 book ai didi

c++ - fseek() 将指针设置到错误的位置

转载 作者:行者123 更新时间:2023-11-27 22:55:35 42 4
gpt4 key购买 nike

我有一个具有以下结构的 .dat 文件:

Object name | Area | Length |Form Factor

我正在尝试查找哪个对象具有最小面积。我读取了整个文件并使用 ftell() 跟踪具有最小面积的对象及其位置。当我读完文件后,我将流位置指示器设置为我从 ftell() 获得的任何值。然后我将该行作为最终结果读取,但现在,我读取的是错误的行。

对象.dat:

toy1 12785.00 550.70 23.22
toy2 11506.50 495.63 0.48
Pen 35008.65 1450.98 0.17
Pencil 42788.35 1773.42 0.209
card7 128433.00 1552.67 0.67

代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>

using namespace std;

int main()
{
FILE *cfPtr;
errno_t err;

char name[15];
double area, length, fF;
double minArea = 100000.0;
long address, minAreaAdd;

char string[100];

if ((err = fopen_s(&cfPtr, "objects.dat", "r")) != 0) // Check if we can reach the file
printf("The file 'objecs.dat' was not opened to read.\n");
else
{
while (fgets(string, 100, cfPtr))
{
address = ftell(cfPtr);
sscanf_s(string,"%s %lf %lf %lf", &name, sizeof name, &area, &length, &fF);

if (area < minArea)
{
minArea = area;
minAreaAdd = address;
}
}

cout << "Min Area: " << minArea << " Address: " << minAreaAdd << "\n\n";

fseek(cfPtr, minAreaAdd, SEEK_SET);
fgets(string, 100, cfPtr);
sscanf_s(string, "%s %lf %lf %lf", &name, sizeof name, &area, &length, &fF);

cout << "Name: " << name << " Area : " << area << " Length: " << length << " Form factor: " << fF << "\n";

fclose(cfPtr);
}
return 0;
}

输出:

Min Area: 11506.5 Address: 55

Name: Pen Area : 35008.7 Length: 1450.98 Form factor: 0.17

最佳答案

当您获得文件位置并将其存储到 address 时,那是在您读入该行之后,因此当您寻求它以获取答案时,您将获得该行 正确的之后。

关于c++ - fseek() 将指针设置到错误的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458328/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com