-2

I need to read a file name, but I want my code working for names contains space. How to read until end of line from keyboard?

My code:

#define szoveghosz 256
//....
char bemenet[szoveghosz]; 
fgets (bemenet,sizeof(bemenet),stdin);
zarnilord
  • 43
  • 10
  • 2
    Please describe how your code is broken, ie what result you get and what you expect instead (it looks ok at a first glance). It would also be helpful to have identifiers in your code in *english language*. –  Jun 05 '17 at 11:38
  • for me if i want to read a text from keyboard it saves in "bemenet" array until the first space. – zarnilord Jun 05 '17 at 11:40
  • Consider using [getline(3)](http://man7.org/linux/man-pages/man3/getline.3.html), then parse manually the line which has been read. – Basile Starynkevitch Jun 05 '17 at 11:41
  • 3
    BTW, with a `;` in the `#define szoveghosz 256;` line your code should not compile. So remove that semicolon. – Basile Starynkevitch Jun 05 '17 at 11:42
  • @zarnilord I don't believe you. – melpomene Jun 05 '17 at 11:42
  • 1
    fgets is right, assuming you can put a reasonably small (eg 1000) bound on maximum acceptable input. – Malcolm McLean Jun 05 '17 at 11:42
  • 1
    only consider `getline()` if you only target systems conforming to POSIX.1-2008 and later (ok for linux, not ok for windows, for example) –  Jun 05 '17 at 11:43
  • @FelixPalmen: the question is tagged Linux – Basile Starynkevitch Jun 05 '17 at 11:44
  • @BasileStarynkevitch yes, it is, but as the presented snippet is portable standard-c so far, I think this is worth mentioning ;) –  Jun 05 '17 at 11:45

1 Answers1

2

Read carefully the documentation of fgets(3) (which might be locally available on your Linux computer with man fgets)

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

As documented, fgets will (when possible) keep the newline character. You probably want to remove it. So I recommend coding instead

 memset (bemenet, 0, sizeof(bemenet)); // clear the buffer
 if (fgets(bemenet, sizeof(bemenet), stdin)) {
    char *eol = strchr(bemenet, '\n');
    if (eol) 
       *eol = '\0';
    /// do appropriate things on bemenet
 }

See also strchr(3) & memset(3)

But as I commented, on Linux and POSIX systems, getline(3) is preferable (because it is allocating dynamically an arbitrarily long line). See this.

Notice that (in principle) a filename could contain a newline (but in most cases, you can forget that possibility). See also glob(3) & wordexp(3) and glob(7) and path_resolution(7).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547