谁能帮助我优化代码以读取标准输入。这就是我现在所拥有的:
unsigned char *msg;
size_t msgBytes = 0;
size_t inputMsgBuffLen = 1024;
if ( (msg = (unsigned char *) malloc(sizeof(unsigned char) * inputMsgBuffLen) ) == NULL ) {
quitErr("Couldn't allocate memmory!", EXIT_FAILURE);
}
for (int c; (c = getchar()) != EOF; msgBytes++) {
if (msgBytes >= (inputMsgBuffLen)) {
inputMsgBuffLen <<= 1;
if ( ( msg = (unsigned char *)realloc(msg, sizeof(unsigned char) * inputMsgBuffLen) ) == NULL) {
free(msg);
quitErr("Couldn't allocate more memmory!", EXIT_FAILURE);
}
}
msg[msgBytes] = (unsigned char)c;
}
最佳答案
问题:您是从stdin
读取二进制数据还是文本数据?如果是文本,为什么要使用unsigned char
?
一些忠告:
将所有演员表放在malloc
和realloc
上;它们是不必要的,会使代码混乱。
不要重复调用getchar
,而是使用fread
或fgets
(取决于您是读取二进制还是文本);
请记住,realloc
可能会返回NULL,因此您想将结果分配给一个临时值,否则您将失去对原始指针的跟踪并结束内存泄漏;
为每个输入块使用静态分配的缓冲区;
对对象而不是类型使用sizeof
;这样会更清洁一些,并且可以在类型更改时为您提供保护(例如T *p = malloc(sizeof *p * number_of_elements);
。
假设您打算使用无符号字符的清理版本:
#define inputBufSize 1024
unsigned char *msg = NULL;
size_t msgBytes = 0;
size_t inputMsgBufSize = 0;
unsigned char inputBuffer[inputBufSize];
size_t bytesRead = 0;
while ((bytesRead = fread(
inputBuffer, // target buffer
sizeof inputBuffer, // number of bytes in buffer
1, // number of buffer-sized elements to read
stdin)) > 0)
{
unsigned char *tmp = realloc(msg, inputMsgBufSize + bytesRead));
if (tmp)
{
msg = tmp;
memmove(&msg[inputMsgBufSize], inputBuffer, bytesRead);
inputMsgBufSize += bytesRead;
}
else
{
printf("Ran out of memory\n");
free(msg);
break;
}
}
关于c - 有效的stdin阅读C编程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5638999/