std::fsetpos
來自 cppreference.com
定義於標頭檔案 <cstdio> |
||
int fsetpos( std::FILE* stream, const std::fpos_t* pos ); |
||
根據 pos
指向的值,設定 C 檔案流 stream
的檔案位置指示器和多位元組解析狀態(如果有)。
除了建立新的解析狀態和位置之外,此函式的呼叫還會撤銷 std::ungetc 的效果,並清除檔案結束狀態(如果已設定)。
如果發生讀寫錯誤,則設定流的錯誤指示器(std::ferror)。
目錄 |
[編輯] 引數
stream | - | 要修改的檔案流 |
pos | - | 指向一個 fpos_t 物件的指標,該物件透過對與同一檔案關聯的流呼叫 std::fgetpos 獲得 |
[編輯] 返回值
成功時返回 0,否則返回非零值。失敗時還會設定 errno。
[編輯] 注意
在寬流中尋找到非結束位置後,下次呼叫任何輸出函式可能會使檔案的其餘部分未定義,例如,透過輸出不同長度的多位元組序列。
[編輯] 示例
執行此程式碼
#include <cstdio> #include <cstdlib> int main() { // Prepare an array of floating-point values. const int SIZE = 5; double A[SIZE] = {1., 2., 3., 4., 5.}; // Write array to a file. std::FILE * fp = std::fopen("test.bin", "wb"); std::fwrite(A, sizeof(double), SIZE, fp); std::fclose(fp); // Read the values into array B. double B[SIZE]; fp = std::fopen("test.bin", "rb"); std::fpos_t pos; if (std::fgetpos(fp, &pos) != 0) // current position: start of file { std::perror("fgetpos()"); std::fprintf(stderr, "fgetpos() failed in file %s at line # %d\n", __FILE__, __LINE__-3); std::exit(EXIT_FAILURE); } int ret_code = std::fread(B, sizeof(double), 1, fp); // read one value // current position: after reading one value std::printf("%.1f; read count = %d\n", B[0], ret_code); // print one value and ret_code if (std::fsetpos(fp, &pos) != 0) // reset current position to start of file { if (std::ferror(fp)) { std::perror("fsetpos()"); std::fprintf(stderr, "fsetpos() failed in file %s at line # %d\n", __FILE__, __LINE__-5); std::exit(EXIT_FAILURE); } } ret_code = std::fread(B, sizeof(double), 1, fp); // re-read first value std::printf("%.1f; read count = %d\n", B[0], ret_code); // print one value and ret_code std::fclose(fp); return EXIT_SUCCESS; }
輸出
1.0; read count = 1 1.0; read count = 1
[編輯] 參閱
獲取檔案位置指示器 (函式) | |
返回當前檔案位置指示器 (函式) | |
將檔案位置指示器移動到檔案中特定位置 (函式) | |
C documentation 關於 fsetpos
|