C: error replacing gets() with fgets() -


i having issue replacing gets() fgets(). have looked @ multiple examples of doing , seems straight forward getting unexpected output in doing so. using gets() method in comments below, behavior shell program writing, when change fgets() call, output ": no such file or directory" when giving input "ls". said, gets() call working fine. code below:

int main(void) {    while(1) {     int = 0;     printf("$shell: ");      scanf("%s", first);     /* gets(input);*/     fgets(input, sizeof(input), stdin);      //...parse input tokens exec system call...      execvp(first, args);    }   return 0; } 

unlike gets, fgets read newline , store in string.

from man page:

fgets() reads in @ 1 less size characters stream , stores them buffer pointed s. reading stops after eof or newline. if newline read, stored buffer. '\0' stored after last character in buffer.

you can remove newline (if present) replacing null byte:

fgets(input, sizeof(input), stdin); if (input[strlen(input)-1] == '\n') input[strlen(input)-1] = '\0'; 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -