Usage of fgets function in C

后端 未结 7 1612
野性不改
野性不改 2020-12-19 17:51

One of my assignments in to write my own UNIX Shell. To receive input from the user, I am using fgets to capture the input as a string but I\'m not really sure how it works.

7条回答
  •  情歌与酒
    2020-12-19 18:35

    fgets will always include the line termination character in the input string. You can remove any space, including the newline characters, from the end of your "command" by doing:

    char command[50];
    fgets(command, sizeof(command), stdin);
    
    size_t length = strlen(command);
    // Trim off trailing "spaces" including newline characters
    while ((length > 0) && isspace(command[length-1]))
          command[--length] = '\0';
    
    printf("Your Command: %s\n", &command); // Include newline now...
    // This is computed above...
    // int length = strlen(command);
    
    // Continue as before
    

提交回复
热议问题