2

In C, I am writing a program which is taking in user input than comparing it to see which output it should use. I am finding it problomatic and was wondering if someone could give me a hand. So far I have:

while(cmd[0] != EOF){
     fgets(cmd, sizeof(cmd), stdin); /** Takes in user input and stores it in cmd **/
     if(cmd[0] == '\n')
         printf("%s> ", cwd);
     else if(strcmp(cmd, "ls") == 0)
         printf("I will list everything");
}

Any ideas? Basically it is just ignoring any user input when there is some.

P.S. The variable cwd is just a string.

4
  • What kind of problems are you having? Commented Feb 13, 2011 at 23:22
  • Basically it is ignoring any user input except a new line. Commented Feb 13, 2011 at 23:23
  • @Michael Dillon - It makes perfect sense if it's declared char cmd[128];. If it's a dynamic array then you're right. Commented Feb 14, 2011 at 1:40
  • @Chris- the point is that it is not declared at all in the question. sizeof is supposed to be used only with completely defined types and we cannot see if char *cmd is completely defined. Commented Feb 14, 2011 at 3:00

1 Answer 1

2

I think you need to ask a more specific question. A couple of problems I can see:

  1. The strcmp() call. fgets() will retain the newline (if any) from the input line. Given that your program looks like it's implementing a command line shell, comparing with "ls" is probably never going to be true - you would need to use strncmp() or include the \n in the string you're comparing against.

  2. You're not checking the return status from the fgets() call - you'll probably want to do that to avoid disaster if someone types some bad control characters in at your prompt.

  3. As I mentioned above, your program looks kind of like a command shell. If that's the case, your prompt (the "%s> ", right?) will only get printed out if the user enters a blank line as input. Presumably you would want the prompt to get printed out each time around the loop.

  4. How do you expect cmd[0] to ever be EOF for your loop to complete? The fgets() man page says:

    Upon successful completion, fgets() and gets() return a pointer to the string. If end-of-file occurs before any characters are read, they return NULL and the buffer contents remain unchanged.

    That sounds to me like you can't ever get EOF in your buffer by using fgets().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.