当我使用时fgetpos(fp,&pos),调用设置pos为负值,其中pos类型为fpos_t.有人可以解释为什么会这样吗?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define MAX_TAG_LEN 50
char filename[1000] = "d:\\ire\\a.xml";
//extract each tag from the xml file
int getTag(char * tag, FILE *fp)
{
//skip until a beginning of a next
while(!feof(fp))
if((char)fgetc(fp) == '<')break;
if(!feof(fp)){
char temp[MAX_TAG_LEN]={0};
char *ptr;
int len;
fpos_t b;
fgetpos(fp,&b); // here the b is containing -ve values.....???
fread(temp,sizeof(char),MAX_TAG_LEN - 1,fp);
temp[MAX_TAG_LEN-1] = 0;
ptr = strchr(temp,'>'); //search of ending tag bracket
len = ptr - temp + 1;
sprintf(tag,"<%.*s",len,temp); //copy the tag
printf("%s",tag); //print the tag
b += len; //reset the position of file pointer to just after the tag character.
fsetpos(fp,&b);
return TRUE;
}
else{
return FALSE;
}
}
int main()
{
int ch;
char tag[100]={0};
FILE *fp = fopen(filename,"r");
while(getTag(tag,fp)){
}
fclose(fp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
其中a.xml是一个非常基本的xml文件
<file>
<page>
<title>AccessibleComputing</title>
<id>10</id>
<redirect />
<revision>
<id>133452289</id>
<timestamp>2007-05-25T17:12:12Z</timestamp>
<contributor>
<username>Gurch</username>
<id>241822</id>
</contributor>
<minor />
<comment>Revert edit(s) by [[Special:Contributions/Ngaiklin|Ngaiklin]] to last version by [[Special:Contributions/Rory096|Rory096]]</comment>
<text xml:space="preserve">#REDIRECT [[Computer accessibility]] {{R from CamelCase}}</text>
</revision>
</page>
</file>
Run Code Online (Sandbox Code Playgroud)
该代码适用于某些xml文件,但对于上述xml文件,它在打印第一个标记后停止.
fpos_t对象通常由调用创建,该调用fgetpos返回对此类对象的引用.a的内容fpos_t并不意味着直接读取,而只是在调用时使用其引用作为参数fsetpos.
我认为这意味着理论上a的价值fpos_t可以是任意正面或负面的,只要实施正确对待它.例如,fpos_t可能是文件末尾的一些偏移而不是开头,在这种情况下负值是有意义的.它也可能是一些奇怪的位打包表示,它将使用每个位(包括符号位)来编码有关文件位置的一些其他信息.