]> granicus.if.org Git - python/commitdiff
Issue #5008: When a file is opened in append mode with the new IO library,
authorAntoine Pitrou <solipsis@pitrou.net>
Wed, 21 Jan 2009 00:45:36 +0000 (00:45 +0000)
committerAntoine Pitrou <solipsis@pitrou.net>
Wed, 21 Jan 2009 00:45:36 +0000 (00:45 +0000)
do an explicit seek to the end of file (so that e.g. tell() returns the
file size rather than 0). This is consistent with the behaviour of the
traditional 2.x file object.

Lib/test/test_io.py
Misc/NEWS
Modules/_fileio.c

index 967018ea453a0372641ee5f50f69292ff828c9d2..f0b38b6f7a94b0b1bdfbbfb9354d50c15f459307 100644 (file)
@@ -232,6 +232,17 @@ class IOTest(unittest.TestCase):
             else:
                 self.fail("1/0 didn't raise an exception")
 
+    # issue 5008
+    def test_append_mode_tell(self):
+        with io.open(test_support.TESTFN, "wb") as f:
+            f.write(b"xxx")
+        with io.open(test_support.TESTFN, "ab", buffering=0) as f:
+            self.assertEqual(f.tell(), 3)
+        with io.open(test_support.TESTFN, "ab") as f:
+            self.assertEqual(f.tell(), 3)
+        with io.open(test_support.TESTFN, "a") as f:
+            self.assert_(f.tell() > 0)
+
     def test_destructor(self):
         record = []
         class MyFileIO(io.FileIO):
index a3f0242ca9b6d086b5f070a352ad5cdddd719189..204ea809158630175217cffa9ee16065918990b3 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -145,6 +145,11 @@ Core and Builtins
 Library
 -------
 
+- Issue #5008: When a file is opened in append mode with the new IO library,
+  do an explicit seek to the end of file (so that e.g. tell() returns the
+  file size rather than 0). This is consistent with the behaviour of the
+  traditional 2.x file object.
+
 - Issue #5013: Fixed a bug in FileHandler which occurred when the delay
   parameter was set.
 
index 2a86e07e4369f707a7b044e812ce99050c67ca10..2fc6de887a8b2d347b9d63a7c7f5f36db85647ff 100644 (file)
@@ -41,6 +41,9 @@ PyTypeObject PyFileIO_Type;
 
 #define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
 
+static PyObject *
+portable_lseek(int fd, PyObject *posobj, int whence);
+
 /* Returns 0 on success, errno (which is < 0) on failure. */
 static int
 internal_close(PyFileIOObject *self)
@@ -296,6 +299,16 @@ fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
                        goto error;
        }
 
+       if (append) {
+               /* For consistent behaviour, we explicitly seek to the
+                  end of file (otherwise, it might be done only on the
+                  first write()). */
+               PyObject *pos = portable_lseek(self->fd, NULL, 2);
+               if (pos == NULL)
+                       goto error;
+               Py_DECREF(pos);
+       }
+
        goto done;
 
  error: