2011-01-18 115 views
2

當我使用fgetpos(fp,&pos)時,呼叫將pos設置爲負值,其中pos的類型爲fpos_t。有人可以解釋爲什麼會發生這種情況嗎?爲什麼fgetpos()返回負偏移量?

#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; 
} 

其中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> 

該代碼是工作了一段XML文件,但因上述XML文件正在打印的第一個標籤後回採。

+3

請張貼的完整代碼您使用的是FPOS – Ass3mbler 2011-01-18 21:08:05

回答

9

根據the cplusplus.com description of fpos_t

fpos_t對象通常是通過以fgetpos的呼叫時,它返回到該類型的一個對象的引用創建的。 fpos_t的內容並不是要直接讀取,而只是將其參考用作調用fsetpos時的參數。

我認爲這意味着理論上fpos_t的值可以是任意正數或負數,只要實現正確處理它。例如,fpos_t可能與文件的結尾有些偏移,而不是開始,在這種情況下,負值是有意義的。它也可能是一些奇怪的比特填充表示,它會使用包括符號位在內的每一位來編碼關於文件位置的一些其他信息。

+0

右`fpos_t`是一個* opaque類型就像`FILE`一樣,你永遠不應該嘗試訪問它的內部,因爲它們是實現定義的。 +1 – SiegeX 2011-01-18 21:22:34

0

終於讓我找到了錯誤....

MSDN說

您可以使用FSEEK隨時隨地重新定位 指針在文件中。 指針也可以位於文件末尾的 之外。 fseek清除 文件結束指示符,並抵消任何先前未收到的呼叫 針對流的影響 。

當一個文件被打開用於附加 數據,當前文件位置是 由最後的I/O操作而確定, 不會發生 下一個寫入位置。如果還沒有I/O操作 發生在爲 追加打開的文件上,則文件位置爲該文件的起始位置 。

以文本方式打開流,FSEEK很少用到,因爲 回車換行符翻譯 可引起FSEEK產生意想不到的結果 。保證對工作流的唯一FSEEK操作 打開 在文本模式有:

與0相對 任何起源值的偏移追求。從文件的開始處尋找 ,並將 偏移值從調用返回到 ftell。

一次fopen的調用由「R」爲「RB」它工作得很好修飾....

感謝

相關問題