次の2つのファイルについて考えてみます。
file1.txt(Windows改行)
abc\r\n
def\r\n
file2.txt(Unix改行)
abc\n
def\n
file2.txtの場合、で取得した位置fgetpos
が正しくインクリメントされないことに気づきました。私はWindowsに取り組んでいます。
例を示しましょう。次のコード:
#include<cstdio>
void read(FILE *file)
{
int c = fgetc(file);
printf("%c (%d)\n", (char)c, c);
fpos_t pos;
fgetpos(file, &pos); // save the position
c = fgetc(file);
printf("%c (%d)\n", (char)c, c);
fsetpos(file, &pos); // restore the position - should point to previous
c = fgetc(file); // character, which is not the case for file2.txt
printf("%c (%d)\n", (char)c, c);
c = fgetc(file);
printf("%c (%d)\n", (char)c, c);
}
int main()
{
FILE *file = fopen("file1.txt", "r");
printf("file1:\n");
read(file);
fclose(file);
file = fopen("file2.txt", "r");
printf("\n\nfile2:\n");
read(file);
fclose(file);
return 0;
}
そのような結果を与える:
file1:
a (97)
b (98)
b (98)
c (99)
file2:
a (97)
b (98)
(-1)
(-1)
file1.txtは期待どおりに機能しますが、file2.txtは奇妙な動作をします。何が問題なのかを説明するために、次のコードを試しました。
void read(FILE *file)
{
int c;
fpos_t pos;
while (1)
{
fgetpos(file, &pos);
printf("pos: %d ", (int)pos);
c = fgetc(file);
if (c == EOF) break;
printf("c: %c (%d)\n", (char)c, c);
}
}
int main()
{
FILE *file = fopen("file1.txt", "r");
printf("file1:\n");
read(file);
fclose(file);
file = fopen("file2.txt", "r");
printf("\n\nfile2:\n");
read(file);
fclose(file);
return 0;
}
私はこの出力を得ました:
file1:
pos: 0 c: a (97)
pos: 1 c: b (98)
pos: 2 c: c (99)
pos: 3 c:
(10)
pos: 5 c: d (100)
pos: 6 c: e (101)
pos: 7 c: f (102)
pos: 8 c:
(10)
pos: 10
file2:
pos: 0 c: a (97) // something is going wrong here...
pos: -1 c: b (98)
pos: 0 c: c (99)
pos: 1 c:
(10)
pos: 3 c: d (100)
pos: 4 c: e (101)
pos: 5 c: f (102)
pos: 6 c:
(10)
pos: 8
fpos_t
実装に依存しているので、それはコーダーによって解釈されることを意図していないことを私は知っています。ただし、上記の例ではfgetpos
/の問題について説明していますfsetpos
。
改行シーケンスが、その文字に遭遇する前であっても、ファイルの内部位置にどのように影響する可能性がありますか?