结合使用getline和动态存储 [英] Using getline along with dynamic storage

查看:93
本文介绍了结合使用getline和动态存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码段.我遇到了几个例子,其中一个人可以使用getline读取一行,然后简单地将其打印出来.我正在努力从stdin中连续保存,使用getline()进行读取,并且可能有某种缓冲区来跟踪所有读取的内容(是否需要?).

I have the following snippet. I have come across several examples where one can read a line using getline and then simply print it. I am struggling to continuously save from stdin, read using getline() and probably have a buffer of some sort to keep track of all that is read (is it needed?).

最终,我只按照用户输入的最后一行的相反顺序打印内容.我不确定char *是否可以指向整个stdin输入缓冲区,我们最终是否可以反向读取.

Eventually, I just print the contents in reverse order of the user's input last line first. I am not sure if char* can point to the entire buffer os stdin input, that we can reverse read eventually.

这遇到了分段错误,我最好的猜测是围绕访问从未分配的内存.

This is running into segmentation fault, my best guess would be around accessing memory that was never allocated.

  size_t linecount = 0;
  ssize_t bytes_read;
  size_t nbytes = 100;
  char *content;

  if (1) {
    my_string = (char*) malloc(nbytes + 1);
    while ((bytes_read = getline(&my_string, &nbytes, stdin)) >= 0
        && my_string[0] != '\n') {
      puts(my_string);
      printf("read: %ld bytes", bytes_read);
      content = (char*) malloc((strlen(my_string) + 1) * sizeof(char));
      success = content != NULL;

      if (success) {
        strcpy(content, my_string);
        ++linecount;
      } else {
        printf("Malloc error\n");
        exit(1);
      }
    }
  }

推荐答案

由于目标是以与用户输入相反的顺序打印内容,最后一行在前",因此程序必须存储所有行. getline()函数通常为每行分配相当大的空间(在我的Mac上默认为128字节,如果输入行长于此则增加),因此通常最好有一个缓冲区由 getline()管理,可以根据需要进行扩展,并将实际的输入字符串复制到其他具有所需长度的位置.我使用 strdup()复制行.

Since the goal is "print the contents in reverse order of the user's input, last line first", the program must store all the lines. The getline() function typically allocates quite a large space for each line (128 bytes by default on my Mac, and growing if input lines are longer than that), so it is usually best to have a buffer managed by getline() that can grow if need be, and to copy the actual input strings somewhere else with the requisite length. I use strdup() to copy the line.

/* Read file and print the lines in reverse order */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char **ptrs = 0;
    size_t numptrs = 0;
    size_t count = 0;
    char  *buffer = 0;
    size_t buflen = 0;

    while (getline(&buffer, &buflen, stdin) != -1)
    {
        if (count == numptrs)
        {
            size_t newnum = (numptrs + 2) * 2;
            void *newptrs = realloc(ptrs, newnum * sizeof(*ptrs));
            if (newptrs == 0)
            {
                fprintf(stderr, "Out of memory (%zu bytes requested)\n", newnum * sizeof(*ptrs));
                exit(1);
            }
            ptrs = newptrs;
            numptrs = newnum;
        }
        ptrs[count++] = strdup(buffer);
    }

    free(buffer);

    /* Print lines in reverse order */
    for (size_t i = count; i > 0; i--)
        fputs(ptrs[i-1], stdout);

    /* Free allocated memory */
    for (size_t i = 0; i < count; i++)
        free(ptrs[i]);
    free(ptrs);

    return 0;
}

容易争论的是,代码应检查 strdup()是否成功,如果不成功,则应采取适当的措施.释放分配的内存的代码应该在一个函数中,该函数也将使错误发生后的清理更加容易.该代码可以修改为一个函数,该函数可用于处理列为命令行参数而不是标准输入的文件.

It's easy to argue that the code should check that strdup() succeeds and take appropriate action if it does not. The code freeing the allocated memory should be in a function — that would make clean up after an error easier, too. The code could be revised into a function that could be used to process files listed as command-line arguments instead of standard input.

将此文本作为标准输入:

Given this text as standard input:

Because it messes up the order in which people normally read text.
> Why is top-posting such a bad thing?
>> Top-posting.
>>> What is the most annoying thing in e-mail?

程序产生输出:

>>> What is the most annoying thing in e-mail?
>> Top-posting.
> Why is top-posting such a bad thing?
Because it messes up the order in which people normally read text.

这篇关于结合使用getline和动态存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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