gpt4 book ai didi

c - 使用 ftell 读取文本文件中数据的偏移量

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:34 25 4
gpt4 key购买 nike

所以我有一个文本文件,其中存储了数据。现在我想计算每个数据在其中的位置,所以我使用了下面的方法。

        while (fscanf(fp, "%d", &id) != EOF) {
offset = ftell(fp);
}

现在的问题是,通过这段代码我得到了数据结尾的位置,所以下一个数据的开始。我怎样才能始终获得数据的开头,所以从 0 开始?

最佳答案

使用这个

while (fscanf(fp, "%d%n", &id, &length) != EOF) {
offset = ftell(fp) - length;
}

来自 scanf() linux 手册

n      Nothing is expected; instead, the number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer  to  int.
This is not a conversion, although it can be suppressed with the * assignment-suppression character. The C standard says: "Execution of a %n directive does
not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any
assumptions on the effect of %n conversions on the return value.

关于c - 使用 ftell 读取文本文件中数据的偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28024696/

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