有效读取标准输入c编程 [英] Effective stdin reading c programming

查看:163
本文介绍了有效读取标准输入c编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能帮助我optimalize code读取标准输入。这是我现在有:

 无符号字符*味精;
为size_t msgBytes = 0;
为size_t inputMsgBuffLen = 1024;
如果((味精=(无符号字符*)malloc的(sizeof的(无符号字符)* inputMsgBuffLen))== NULL){
    quitErr(无法分配memmory!,EXIT_FAILURE);
}
对于(INT℃;(C =的getchar())= EOF;!msgBytes ++){
    如果(msgBytes> =(inputMsgBuffLen)){
        inputMsgBuffLen&所述;&下; = 1;
        如果((味精=(无符号字符*)的realloc(味精,sizeof的(无符号字符)* inputMsgBuffLen))== NULL){
            免费(MSG);
            quitErr(无法分配更多memmory!,EXIT_FAILURE);
        }
    }
    味精[msgBytes] =(unsigned char型)C;
}


解决方案

问:你从标准输入读取二进制或文本数据?如果文本,你为什么使用 unsigned char型

的几点建议:


  1. 删除所有石膏的malloc 的realloc ;他们是没有必要的,凌乱的code;

  2. 而不是反复调用的getchar ,使用 FREAD 与fgets (取决于你正在阅读二进制或文本);

  3. 记住的realloc 有可能返回NULL,所以你要的结果分配给一个临时的值,否则你会失去跟踪原指针和风能泄漏内存;

  4. 使用为每个输入块静态分配的缓冲区;

  5. 使用的sizeof 的对象,而不是类型;这是一个少许清洁剂,它可以保护你的情况下,类型更改(例如, T * p =的malloc(sizeof的* P * number_of_elements);

清理后的版本假设你打算使用无符号的字符:

 的#define inputBufSize 1024无符号字符*味精= NULL;
为size_t msgBytes = 0;
为size_t inputMsgBufSize = 0;
unsigned char型INPUTBUFFER [inputBufSize]
为size_t读取动作= 0;而((读取动作= FREAD(
    INPUTBUFFER,//目标缓冲区
    sizeof的INPUTBUFFER,//缓冲区的字节数
    1,//缓冲器大小的元素的数目,以读
    标准输入))> 0)
{
  无符号字符* TMP = realloc的(味精,inputMsgBufSize +读取动作));
  如果(TMP)
  {
    味精= tmp目录;
    memmove与(安培;味精[inputMsgBufSize],INPUTBUFFER,读取动作);
    inputMsgBufSize + =读取动作;
  }
  其他
  {
    的printf(冉出内存的\\ n);
    免费(MSG);
    打破;
  }
}

can anyone help me optimalize code for reading standard input. Here it is what I have now:

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;
}

解决方案

Question: are you reading binary or text data from stdin? If text, why are you using unsigned char?

Some advice:

  1. Drop all the casts on malloc and realloc; they aren't necessary and clutter up the code;
  2. Instead of repeatedly calling getchar, use fread or fgets (depending on whether you're reading binary or text);
  3. Remember that realloc can potentially return NULL, so you want to assign the result to a temporary value, otherwise you'll lose track of the original pointer and wind up leaking memory;
  4. Use a statically allocated buffer for each chunk of input;
  5. Use sizeof on objects, not types; it's a little cleaner, and it protects you in case the types change (e.g., T *p = malloc(sizeof *p * number_of_elements);.

Cleaned-up version assuming you intend to use unsigned chars:

#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编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆