namespace std {
int fgetpos(FILE* stream, fpos_t* pos);
}
概要
ファイルの現在位置を取得する。
戻り値
正常に実行されれば0を返す。
失敗した場合は、0以外を返し、エラーの内容はerrnoから参照することができる。
この機能が必要になった背景・経緯
かつてはftellで位置を取得していたが、ftellは位置をlong intで返すため、非常に大きなファイルやマルチバイト文字を含む特殊なファイルでは正確に表現できないことがあった。
そこで、どのようなファイルでも位置を正確に表現できるfpos_t型が導入されたことに伴い、この関数が登場した。
例
#include <iostream>
#include <cstdio>
int main() {
std::FILE *file = std::fopen("example.txt", "w");
if (file == nullptr) {
std::perror("Failed to open file");
return 1;
}
std::fpos_t current_pos;
std::fgetpos(file, ¤t_pos);
std::fputs("Hello, World!\n", file);
std::fsetpos(file, ¤t_pos);
std::fputs("h", file);
std::fclose(file);
file = std::fopen("example.txt", "r");
if (file == nullptr) {
std::perror("Failed to open file");
return 1;
}
int ch;
while ((ch = std::fgetc(file)) != EOF) {
std::putchar(ch);
}
std::fclose(file);
return 0;
}
出力
hello, World!
処理系
- Clang: ??
- GCC: ??
- Visual C++: ??