5 Cách mở file trong python

1

#define PY_SSIZE_T_CLEAN

2

#include <Python.h>

3

4

5

PyObject

*

mwgread

(

PyObject

*

self

,

PyObject

*

args

)

{

6

7

8

FILE

*

pFile

;

9

size_t

lSize

;

10

char

*

buffer

;

11

size_t

result

;

12

13

//

Parse

the

Python

object

arguments

into

C

variables

14

char

*

filename

;

15

if

(

!

PyArg_ParseTuple

(

args

,

"s"

,

&

filename

))

{

16

return

NULL

;

17

}

18

19

//

Try

to

open

the

file

20

pFile

=

fopen

(

filename

,

"r"

);

21

if

(

pFile

==

NULL

)

{

22

return

NULL

;

23

}

24

25

//

obtain

file

size

:

26

fseek

(

pFile

,

0

,

SEEK_END

);

27

lSize

=

ftell

(

pFile

);

28

rewind

(

pFile

);

29

30

//

allocate

memory

to

contain

the

whole

file

:

31

buffer

=

(

char

*

)

malloc

(

sizeof

(

char

)

*

lSize

);

32

if

(

buffer

==

NULL

)

{

fputs

(

"Memory error"

,

stderr

);

exit

(

2

);}

33

34

//

copy

the

file

into

the

buffer

:

35

result

=

fread

(

buffer

,

1

,

lSize

,

pFile

);

36

if

(

result

!=

lSize

)

{

fputs

(

"Reading error"

,

stderr

);

exit

(

3

);}

37

38

/*

the

whole

file

is

now

loaded

in

the

memory

buffer

.

*/

39

40

//

terminate

41

fclose

(

pFile

);

42

return

Py_BuildValue

(

"s"

,

buffer

);

43

}

44

45

46

PyMethodDef

module_methods

[]

=

{

47

{

"read"

,

mwgread

,

METH_VARARGS

,

"Reads a file and returns its contents"

},

48

{

NULL

}

49

};

50

51

struct

PyModuleDef

file_module

=

{

52

PyModuleDef_HEAD_INIT

,

53

"MWGFile"

,

54

NULL

,

55

-

1

,

56

module_methods

57

};

58

59

PyMODINIT_FUNC

PyInit_MWGFile

(

void

)

{

60

return

PyModule_Create

(

&

file_module

);

61

}