Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 04 Jan 2001 19:52:13 -0500
From:      Chris Williams <psion@geekspace.com>
To:        freebsd-hackers@freebsd.org
Cc:        rozzin@geekspace.com
Subject:   Strange fwrite() behavior in a+ mode
Message-ID:  <3A551ABD.DBC9BD5C@geekspace.com>

next in thread | raw e-mail | index | archive | help
If I run the following program, I get the following results:

---
jello:/usr/home/chris/foo$ cat blah.c
#include <stdio.h>
int main() {
  FILE *f = fopen("foo", "a+");
  char x[50] = "                          ";
  char y[50] = "                          ";
  fseek(f, 0, SEEK_SET);
  printf("tell: %d\n", ftell(f));
  printf("fread return'd: %d\n", fread(x, (size_t) 1, (size_t)3, f));
  printf("read: %s\n", x);
  printf("tell: %d\n", ftell(f));
  fwrite("xxx", (size_t) 1, (size_t) 3, f);
  printf("tell: %d\n", ftell(f));
  printf("fread return'd: %d\n", fread(y, (size_t) 1, (size_t)3, f));
  printf("read: %s\n", y);
  printf("tell: %d\n", ftell(f));

}

jello:/usr/home/chris/foo$ cat foo
123456789
jello:/usr/home/chris/foo$ cc blah.c -o bar;./bar
tell: 0
fread return'd: 3
read: 123
tell: 3
tell: 13
fread return'd: 0
read:
tell: 13
jello:/usr/home/chris/foo$
---

But, if I comment out the read before the write, I get somewhat strange
behavior:

---
jello:/usr/home/chris/foo$ cat blah.c
#include <stdio.h>
int main() {
  FILE *f = fopen("foo", "a+");
  char x[50] = "                          ";
  char y[50] = "                          ";
  fseek(f, 0, SEEK_SET);
  printf("tell: %d\n", ftell(f));
//  printf("fread return'd: %d\n", fread(x, (size_t) 1, (size_t)3, f));
//  printf("read: %s\n", x);
  printf("tell: %d\n", ftell(f));
  fwrite("xxx", (size_t) 1, (size_t) 3, f);
  printf("tell: %d\n", ftell(f));
  printf("fread return'd: %d\n", fread(y, (size_t) 1, (size_t)3, f));
  printf("read: %s\n", y);
  printf("tell: %d\n", ftell(f));

}

jello:/usr/home/chris/foo$ cat foo
123456789
jello:/usr/home/chris/foo$ cc blah.c -o bar;./bar
tell: 0
tell: 0
tell: 3
fread return'd: 0
read:
tell: 13
jello:/usr/home/chris/foo$
---

It tells me I'm at 3, but my read acts as if I'm at the end of the file, and
then after trying to read it tells me I'm at 13 (the end).

Is this a bug? Am I doing something illegal, and the behavior is random? Or..?

According to Rozzin (CCed, who brought the issue to my attention), under Linux
he sees the first behavior (move pointer to end of file, and tell you that)
consistantly.


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?3A551ABD.DBC9BD5C>