C - fsetpos没有按预期设置文件指针's位置


//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 

所以,我建议我自己:

  1. 使用fseek。我为什么要自找麻烦?不,我不会用的。如果我要使用它,我将需要编写超过50行代码。效率低下。
  2. 使用fseek,但不像建议#1。使用它与fsetpos像这样:fsetpos更新pos1 &pos2变量,然后使用它们-通过"a"一些代码-作为fseek函数中offset参数的参数!这是一个非常好的想法,但它有两个缺点:首先:pos1pos2是一种奇怪的数据类型。我怎么能让他们进入偏移参数,他们的数据类型不匹配。第二,我试图从叶子上而不是从根源上解决问题。效率低下。
  3. 发布在这里。

您的第二个fgetpos可能是fsetpos的错别字。这就解释了你评论的行为:

pos2现在被替换为一个新值,比如18。

编辑后更新:现在两个调用都是fsetpos ??你需要在某个位置get,然后再用set回到它。

相关内容

  • 没有找到相关文章

最新更新