【发布时间】:2015-07-25 15:26:16
【问题描述】:
//This is an *abstract* from my code:
FILE* fpointer;
fpos_t pos1,pos2;
// make a do-while loop
do{
// I am reading a text file word by word
c = fscanf(fpointer, "%s", temp);
/* a code *begins* here. I am doing parsing
stuff
stuff
stuff
*/
// Now I am going to store the file pointer's position somewhere in the text
fgetpos (fpointer , &pos1);
//let us say that pos1 is now equal to 7
// I am gonna store the value 7 into pos2. I will explain why later
pos2=pos1;
/* the parsing code continues here.
stuff
stuff
stuff
*/
// Now I want to get back to the position # 7
fgetpos (fpointer , &pos2);
// The problem is this after executing the previous line of code:
/*
pos2 is replaced now with a new value let us say 18.
I do not if this a real problem but the file pointer's position could not be
modified to get back to 7
I will list my research effort:
1- I looked up many examples in the internet. I always see them using the fsetpos twice. Mine is used twice in one loop... not sure if there is a mistake in using it like that?!
2- I saw some examples use 2 variables instead of one. for example pos1 and pos2 but it did not fix the problem.
3- There is a chance that I misunderstood the function that it really just stores the position of the file pointer but it probably cannot modify it. However
this argument is invalid because I saw many examples that they use to set the pointer into the beginning of the file (although my code wants to set it to the middle not the beginning).
4- Unexpected behavior and more info wanted.
*/
}while(/*stuff*/);
// End of the code format
所以,我给自己建议:
- 使用
fseek。为什么我要为此烦恼?不,我不会使用它。如果我要使用它,我将需要编写超过 50 行代码。效率低下。 - 使用
fseek,但不像建议#1 中那样。像这样将它与fsetpos一起使用:fsetpos更新pos1和pos2变量,然后使用它们——通过“a”一些代码——作为fseek函数中偏移参数的参数!这是一个非常好的主意,但它有两个缺点: 首先:pos1和pos2是一种奇怪的数据类型。我怎样才能让它们进入偏移参数并且它们的数据类型不匹配。 第二:我喜欢从它的叶子而不是它的根源来处理问题。效率低下。 - 在这里发帖。
【问题讨论】:
-
您没有在您发布的代码中调用 fsetpos...确保您发布了我们可以重现您的问题的实际、可读的代码。
-
我的意思是这样称呼它-_-
-
“我将因此需要编写超过 50 行代码”是什么意思?调用
fseek需要一行,而不是 50 行。 -
@Gold_Sky 您的最新编辑将两个
fgetpos调用更改为fsetpos,所以现在您使用的是未初始化的变量。 -
这个问题得到如此多反对的原因是 10 秒用 google for
fgetpos告诉你它与fsetpos结合使用,以获取/设置位置。 “fgetpos”的前 5 次点击都提到将其与fsetpos一起使用。