1

I want to read from user's input string of size 16000bytes. fgets only reads 1024 bytes. What can I use instead? I am writing in c and this is my code right now. Is it that I am not using malloc?

char str[16392];

while(fprintf(stderr, "> "), fgets(str, 16392, stdin), !feof(stdin)) { }

Also, readline seems to work.

  while(line = readline("> "), !feof(stdin)) {
    printf("You entered: %s\n", line);
    free(line);  
  }
dreamer_999
  • 1,465
  • 3
  • 17
  • 22
  • 3
    You can use `fgets()` 16 times. – Crowman May 04 '14 at 20:25
  • 3
    `fgets()` has no limit. `char buffer[100000]; fgets(buffer, sizeof buffer, stdin);` – pmg May 04 '14 at 20:25
  • 4
    Remember, `fgets()` is for getting *lines*. If your user is presenting you with a 16,000 character line, you might want to sit them down and have a talk to them about it. – Crowman May 04 '14 at 20:29
  • 2
    Your use of `feof()` is wrong! See [`while( !feof( file ) )` is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong). – pmg May 04 '14 at 20:30
  • 2
    `fgets()` doesn't read strings, it reads lines. You probably have some line separator in your input string and `fgets()` is only reading until that point because of it. – Havenard May 04 '14 at 20:33
  • 1
    What's with the repeated horrible abuse of the comma operator, by the way? – Crowman May 04 '14 at 20:49
  • 1
    @Paul Griffiths, the Polish novelist Jerzy Andrzejewski in “The Gates of Paradise” wrote a 158-page run-on. It's comprised of two sentences and the 2nd is only five words long. Thankfully it was pre-computer. ;) – Duck May 04 '14 at 20:54

2 Answers2

3

Do not replace fgets() with a worse option. fgets() has no limit.

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

    char *buffer;
    size_t size;
    size = 10000000; /* 10m */
    buffer = malloc(size);
    if (!buffer) /* error */;
    if (fgets(buffer, size, stdin) == NULL) /* error */;
    // ...
    free(buffer);
pmg
  • 106,608
  • 13
  • 126
  • 198
  • Thanks for the answer. Wondering is it important to use malloc for the buffer? – dreamer_999 May 04 '14 at 20:32
  • 1
    If you don't, your buffer will be stored in the call stack. The call stack has a limited size, by default 1MB in most compilers, you don't want to abuse its space. – Havenard May 04 '14 at 20:34
0

Perhaps there is an implementation where fgets() has a 1024 byte limit; however, this is not something I have seen before.

An alternative might be fread().

Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28