追加模式下file.tell()写入后返回值不符合预期的技术问询
Python文件对象的tell()方法返回值不符合预期
当以a+b模式打开文件时,调用tell()返回的偏移量并未指向最后写入字节的位置,结果低于预期值。
Python示例代码
# appender.py import sys file = open(sys.argv[1], 'a+b') file.seek(0) file.write(b'56789') print('offset: ', file.tell())
运行步骤及结果
$ printf "01234" > myfile $ python appender.py myfile offset: 5
这里返回的偏移量为5,但预期值应为10(原文件含5字节,写入5字节后总长度为10)。
等效C语言实现
/* appender.c */ #include <stdio.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char **argv){ if (argc!=2){ puts("usage ./test file"); return 1; } int fd = open(argv[1], O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); lseek(fd, 0, SEEK_SET); write(fd, "01234", 5); printf("offset: %ld\n", lseek(fd, 0, SEEK_CUR)); return 0; }
C代码运行结果
$ printf "01234" > myfile $ ./appender myfile offset: 10
C语言实现返回了符合预期的偏移量10。
内容的提问来源于stack exchange,提问作者Isidro Arias
相关产品推荐
相关产品推荐

