Added os specific RsFileUtil::rs_getline

This commit is contained in:
thunder2 2021-12-21 09:03:56 +01:00
parent 38b4c50635
commit 753250b4e8
3 changed files with 60 additions and 1 deletions

View File

@ -409,7 +409,7 @@ bool TorProcess::tryReadControlPort()
char *line = nullptr; char *line = nullptr;
size_t tmp_buffsize = 0; size_t tmp_buffsize = 0;
size_t size = getline(&line,&tmp_buffsize,file); size_t size = RsFileUtil::rs_getline(&line,&tmp_buffsize,file);
ByteArray data = ByteArray((unsigned char*)line,size).trimmed(); ByteArray data = ByteArray((unsigned char*)line,size).trimmed();
free(line); free(line);

View File

@ -26,6 +26,7 @@
#include <wtypes.h> #include <wtypes.h>
#include <io.h> #include <io.h>
#include <namedpipeapi.h> #include <namedpipeapi.h>
#include <errno.h>
#else #else
#include <fcntl.h> #include <fcntl.h>
#endif #endif
@ -49,3 +50,58 @@ int RsFileUtil::set_fd_nonblock(int fd)
return ret; return ret;
} }
ssize_t RsFileUtil::rs_getline(char **lineptr, size_t *n, FILE *stream)
{
/******************* OS SPECIFIC PART ******************/
#ifdef WINDOWS_SYS
if (lineptr == nullptr || n == nullptr || stream == nullptr) {
errno = EINVAL;
return -1;
}
if (*lineptr == nullptr || *n < 1) {
*n = BUFSIZ;
*lineptr = (char*) malloc(*n);
if (*lineptr == nullptr) {
*n = 0;
return -1;
}
}
char *ptr = *lineptr;
while (true) {
int c = fgetc(stream);
if (c == -1) {
if (feof(stream)) {
*ptr = '\0';
return (ssize_t) (ptr - *lineptr);
}
return -1;
}
*ptr = c;
++ptr;
if (c == '\n') {
*ptr = '\0';
return ptr - *lineptr;
}
if (ptr + 2 >= *lineptr + *n) {
size_t new_size = *n * 2;
ssize_t diff = ptr - *lineptr;
char *new_lineptr = (char*) realloc(*lineptr, new_size);
if (new_lineptr == nullptr) {
return -1;
}
*lineptr = new_lineptr;
*n = new_size;
ptr = new_lineptr + diff;
}
}
#else // ie UNIX
return getline(lineptr, n, stream);
#endif
}

View File

@ -22,8 +22,11 @@
#pragma once #pragma once
#include <stdio.h>
namespace RsFileUtil { namespace RsFileUtil {
int set_fd_nonblock(int fd); int set_fd_nonblock(int fd);
ssize_t rs_getline(char **lineptr, size_t *n, FILE *stream);
} }