1 Star 0 Fork 0

dybai/ExtExc

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
mygetline.c 1.59 KB
一键复制 编辑 原始数据 按行查看 历史
dybai 提交于 2016-05-18 15:46 . first import
/*
Copyright 2016 小新de蜡笔
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "mygetline.h"
#define DEFSIZE 128
ssize_t mygetline (int fd, char **line)
{
int i = 0, err = 0;
char ch = 0;
size_t size = DEFSIZE;
char *tmp = NULL;
if (NULL == *line) {
*line = malloc(size);
if (!*line) {
return -ENOMEM;
}
}
memset(*line, 0, size);
for (i = 0; ; i++) {
err = read(fd, &ch, 1);
if (!err) { // EOF
break;
} else if (err < 0) { // ERROR
return -errno;
}
if (i == (size - 2)) {
/*
* realloc(3):
* If the new size is larger than the old size,
* the added memory will not be initialized.
*/
size *= 2;
tmp = malloc(size);
if (!tmp) {
return -ENOMEM;
}
memset(tmp, 0, size);
memcpy(tmp, *line, size / 2);
free(*line);
*line = tmp;
tmp = NULL;
}
//*((*line)++) = ch;
(*line)[i] = ch;
if ('\n' == ch) { // Line end
(*line)[++i] = '\0';
break;
}
}
return i;
}
void mygetline_destroy (char **line)
{
free(*line);
*line = NULL;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/dybai/ExtExc.git
git@gitee.com:dybai/ExtExc.git
dybai
ExtExc
ExtExc
master

搜索帮助