Skip to content
Advertisement

Reading a string, char[] until end of line C

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

Advertisement

Answer

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 ('') 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 = '';
    /// 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).

Advertisement