名稱空間
變體
操作

fsetpos

來自 cppreference.com
< c‎ | io
 
 
檔案輸入/輸出
型別和物件
        
函式
檔案訪問
(C95)
非格式化輸入/輸出
(C95)(C95)
(C95)
(C95)(C95)
(C95)
(C95)

格式化輸入
 
定義於標頭檔案 <stdio.h>
int fsetpos( FILE* stream, const fpos_t* pos );

根據 pos 指向的值,設定檔案流 stream 的檔案位置指示器和多位元組解析狀態(如果有的話)。

除了建立新的解析狀態和位置外,呼叫此函式還會撤銷 ungetc 的效果,並清除檔案結束狀態(如果已設定)。

如果發生讀寫錯誤,則設定流的錯誤指示器 (ferror)。

目錄

[編輯] 引數

stream - 要修改的檔案流
pos - 指向一個 fpos_t 物件的指標,用作檔案位置指示器的新值

[編輯] 返回值

成功時返回 0,否則返回非零值。

[編輯] 注意

在寬流中尋找到非結束位置後,下次呼叫任何輸出函式可能會使檔案的其餘部分未定義,例如,透過輸出不同長度的多位元組序列。

[編輯] 示例

帶錯誤檢查的 fsetpos

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    // Prepare an array of FP (floating-point) values.
    #define SIZE 5
    double A[SIZE] = {1.0, 2.0, 3.0, 4.0, 5.0};
    // Write array to a file.
    FILE * fp = fopen("test.bin", "wb");
    fwrite(A,sizeof(double),SIZE,fp);
    fclose (fp);
 
    // Read the FP values into array B.
    double B[SIZE];
    fp = fopen("test.bin","rb");
    fpos_t pos;
    if (fgetpos(fp, &pos)) // current position: start of file
    {
        perror("fgetpos()");
        fprintf(stderr, "fgetpos() failed in file %s at line # %d\n",
                __FILE__, __LINE__ - 3);
        exit(EXIT_FAILURE);
    }
 
    int ret_code = fread(B,sizeof(double),1,fp); // read one FP value
    // current position: after reading one f-p value
    printf("%.1f; read count = %d\n", B[0], ret_code); // print one FP value and ret_code
 
    if (fsetpos(fp, &pos)) // reset current position to start of file
    {
        if (ferror(fp))
        {
            perror("fsetpos()");
            fprintf(stderr, "fsetpos() failed in file %s at line # %d\n", __FILE__,
                    __LINE__ - 5);
            exit(EXIT_FAILURE);
        }
    }
 
    ret_code = fread(B, sizeof(double), 1, fp); // reread first FP value
    printf("%.1f; read count = %d\n", B[0], ret_code); // print one FP value and ret_code
    fclose(fp);
 
    return EXIT_SUCCESS;
}

可能的輸出

1.0; read count = 1
1.0; read count = 1

[編輯] 參考

  • C23 標準 (ISO/IEC 9899:2024)
  • 7.21.9.3 fsetpos 函式 (p: 待定)
  • C17 標準 (ISO/IEC 9899:2018)
  • 7.21.9.3 fsetpos 函式 (p: 待定)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.21.9.3 fsetpos 函式 (p: 337)
  • C99 標準 (ISO/IEC 9899:1999)
  • 7.19.9.3 fsetpos 函式 (p: 303)
  • C89/C90 標準 (ISO/IEC 9899:1990)
  • 4.9.9.3 fsetpos 函式

[編輯] 另請參閱

獲取檔案位置指示器
(函式) [編輯]
返回當前檔案位置指示器
(函式) [編輯]
將檔案位置指示器移動到檔案中特定位置
(函式) [編輯]
C++ 文件 中的 fsetpos