I would like to know how can I read the charaters into a buffer in Python?
In C code, I can easy decralare the buffer character like char buffer[256];
:
void read_char(int x, char buffer[], int *flag_stop) {
int i, length;
char character;
i = 0;
bzero(buffer, 256);
do {
if ((length = read(x, &character, 1)) <= 0)
{
*flag_stop = 1;
break;
}
buffer[i] = character;
i ;
}
while(c != 0x0A);
}
But I don't know how to do in Python so the code is something like this:
def read_char(x,buffer,**flag_stop):
i = 0
buffer = np.array([], dtype='S64')
while True:
if os.read(x, character, 1) <= 0:
**flag_stop == 1
break
buffer[i] = str(character)
i=i 1
if(character != 0x0A):
break
I have tried with numpy.chararray but I did not work. Any idea for this problem? thank you very much!
CodePudding user response:
Your main problem is that you want in Python write code exactly like in C.
Python would need something like this
def read_char(x):
flag_stop = False # or 0
i = 0
buffer = np.array([], dtype='S64')
while True:
character = os.read(x, 1)
if not character: # if len(character) < 0
flag_stop = True # or 1
break
buffer[i] = character
i = 1
if character != 0x0A:
break
return buffer, flag_stop
# ---
buffer, flag_stop = read_char(file_handler)
I don't like str()
in your code - you may get single byte which is part of mulit-bytes code (like utf-8
) and converting to str()
can only mess it.