1

With this code I found here on Stack:

...
char buffer[256]

while((count=read(0, buffer, 256)) > 1)
   {
   if(buffer[count] = '\n') break;
   }

   buffer[n-1] ='\0';

I can read from the standard input, but I have 2 questions:

  1. Why is '=' used in the if() instead of '=='?
  2. If I press CTRL-C after writing something, how can I keep what I wrote?

Thanks

  • 4
    The use of `=` rather than `==` is probably a typo. It doesn't make sense otherwise. Also, it should probably be `if (buffer[count-1] == '\n')`. – Daniel Fischer Mar 14 '13 at 16:18
  • 2
    It is definitely not a typo, read returns read count. while read count is larger than 1 while loop runs. –  Mar 14 '13 at 16:20
  • @Armin: The question is about the `=` in the `if`, not the `while`. – jxh Mar 14 '13 at 16:58
  • @user315052 Correct , i totally missed if(), Daniel Fischer was right. –  Mar 14 '13 at 17:12

1 Answers1

1

Why is '=' used in the if() instead of '=='?

In the if-statement, it's probably a typo. Because

buffer[count] = '\n'

will always be '\n', and in C thats "true" (non-null).

If I press CTRL-C after writing something, how can I keep what I wrote?

Pressing CTRL-C in the terminal will send a SIGINT to the running process. Normally your application will immediately quit, no matter what it was doing.

You can catch the SIGINT-event with some lines of code, but whats the point of "keeping what you wrote"?

Community
  • 1
  • 1
flyingOwl
  • 244
  • 1
  • 5
  • 1
    `buffer[count]` is also off by one. `^C` usually generates `SIGINT`. – jxh Mar 14 '13 at 17:02
  • Changed it to `SIGINT`. And yes, `buffer[count]` seems to be off by one. – flyingOwl Mar 14 '13 at 17:36
  • 1
    "intermediately" -> "immediately"? – undur_gongor Mar 14 '13 at 17:38
  • @undur_gongor: Of course ;) English is not my first language, so I'm using a spell checker. And I clicked the wrong suggestion. – flyingOwl Mar 14 '13 at 17:41
  • I agree that it makes little sense to keep what I wrote, but that is one of the purposes of this exercise. By the way, does the condition in the while even get to run? – user2170647 Mar 14 '13 at 17:47
  • @user2170647 The condition of the `if` will always run, buffer[count] = '\n' evaluates to `\n` , which is non-zero, which in C is true. – nos Mar 14 '13 at 17:52