gpt4 book ai didi

c - 是否有等效于倒带功能的功能,但仅适用于一个 token ?

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:21 27 4
gpt4 key购买 nike

在C语言中,rewind函数用于将流的位置设置到最开始。我想问一下是否有一个等效的函数可以将流位置向左移动一个标记。

例如,我有一个名为 FooFile.txt 的文件,其中包含几行由“”空格字符分隔的整数序列。

int main()
{
// open file stream.
FILE *FooFile = fopen("FooFile.txt" , "r");
int Bar = 0;

// loop through every integer token in the file stream.
while ( fscanf( FooFile, "%d", &Bar ) == 0 )
{
// I don't want to reset the stream to the very beginning.
// rewind( FooFile );
// I only need to move the stream back one token.

Bar = fscanf ( FooFile, "%d", &Bar )
Bar = fscanf ( FooFile, "%d", &Bar )
}
}

最佳答案

你需要 "%n" 说明符来知道读取了多少个字符,然后你 fseek() 读取了负数的字符,这是一个例子

#include <stdio.h>

int main()
{
FILE * file = fopen("FooFile.txt" , "r");
int bar = 0;
int count = 0;

if (file == NULL)
return -1;

while (fscanf(file, "%d%n", &bar, &count) == 1)
{
fseek(file, -count, SEEK_CUR);
/* if you don't re-scan the value, the loop will be infinite */
fscanf(file, "%d", &bar);
}

return 0;
}

请注意,您的代码中存在错误,fscanf() 不返回读取值,而是返回与说明符匹配的参数数量。

关于c - 是否有等效于倒带功能的功能,但仅适用于一个 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28664586/

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