pie*_*tou 2 c optimization stdin
任何人都可以帮助我优化代码读取标准输入.这就是我现在拥有的:
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;
}
Run Code Online (Sandbox Code Playgroud)
问题:您正在阅读二进制或文本数据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;
}
}
Run Code Online (Sandbox Code Playgroud)