4
Copyright (C) 2010-2012 Tamas Nepusz <ntamas@gmail.com>
6
This program is free software; you can redistribute it and/or modify
7
it under the terms of the GNU General Public License as published by
8
the Free Software Foundation; either version 2 of the License, or
9
(at your option) any later version.
11
This program is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
GNU General Public License for more details.
16
You should have received a copy of the GNU General Public License
17
along with this program; if not, write to the Free Software
18
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23
#include "filehandle.h"
24
#include "py2compat.h"
27
* \ingroup python_interface_filehandle
28
* \brief Constructs a new file handle object from a Python object.
30
* \return 0 if everything was OK, 1 otherwise. An appropriate Python
31
* exception is raised in this case.
33
int igraphmodule_filehandle_init(igraphmodule_filehandle_t* handle,
34
PyObject* object, char* mode) {
37
if (object == 0 || PyLong_Check(object)) {
38
PyErr_SetString(PyExc_TypeError, "string or file-like object expected");
43
(!PyBaseString_Check(object) && !PyFile_Check(object))) {
44
PyErr_SetString(PyExc_TypeError, "string or file handle expected");
49
if (PyBaseString_Check(object)) {
51
handle->object = PyFile_FromObject(object, mode);
53
handle->object = PyFile_FromString(PyString_AsString(object), mode);
55
if (handle->object == 0)
58
handle->object = object;
59
Py_INCREF(handle->object);
62
/* At this stage, handle->object is something we can handle.
63
* In Python 2, we get here only if object is a file object. In
64
* Python 3, object can be anything, and PyFile_FromObject will
65
* complain if the object cannot be converted to a file handle.
68
fp = PyObject_AsFileDescriptor(handle->object);
70
Py_DECREF(handle->object);
73
handle->fp = fdopen(fp, mode);
74
if (handle->fp == 0) {
75
Py_DECREF(handle->object);
76
PyErr_SetString(PyExc_RuntimeError, "fdopen() failed unexpectedly");
80
handle->fp = PyFile_AsFile(handle->object);
81
if (handle->fp == 0) {
82
Py_DECREF(handle->object);
83
PyErr_SetString(PyExc_RuntimeError, "PyFile_AsFile() failed unexpectedly");
92
* \ingroup python_interface_filehandle
93
* \brief Destroys the file handle object.
95
void igraphmodule_filehandle_destroy(igraphmodule_filehandle_t* handle) {
96
if (handle->fp != 0) {
101
Py_XDECREF(handle->object);
106
* \ingroup python_interface_filehandle
107
* \brief Returns the file encapsulated by the given \c igraphmodule_filehandle_t.
109
FILE* igraphmodule_filehandle_get(const igraphmodule_filehandle_t* handle) {