简体   繁体   中英

fgets function is not reading the first character in the input

Here is my code and the system call works when there is just one word with no space or anything between (like enter...).

For example when I use "pwd" the call works but when I use something like ls -l or let's say "cd file1 file2" it erases the first character and doesn't take into account anything after the space.

So when I write "cd file1 file2" only the "d" of "cd" is left. What can i do to prevent that ?

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

void Expert_mode()
{
    printf("Your are now in Expert mode, You are using a basic Shell (good luck) \nWe added the commands 'read_history', 'leave' and 'Easter_egg'. \n");

    int a = 0;
    while(a == 0)
    {

        char* line;

        getchar();

        printf("Choose a command : \n");

        line = malloc(100*sizeof(char));

        fgets(line, 100, stdin);

        if(strcoll(line, "leave") == 0)
        {
            a = 1;
        }
        else if(strcoll(line, "read_history") == 0)
        {
            //read_history();
        }
        else if(strcoll(line, "Easter_egg") == 0)
        {
           // Easter_egg();
        }
        else
        {
            system(line);
        }
    }
}

It's because you have getchar(); call before fgets() call. So it consumes the first character and only the rest of the input is read by fgets() . Remove it.

Also, note that fgets() would read the trailing newline as well, if buffer space is available. You would want to trim it.

You can use strchr() to remove the newline, if present:

fgets(line, 100, stdin);
char *p = strchr(line, '\n');
if (p) *p = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM