I have a quick little question involving the read() command.
I am really rusty in C, and unfortunately, my current assignment has me programming in C.
We need to read stdin using the read() and not fgets and the like.
So I have a simple while loop:
int n, i;
char buffer[257], *input;
while((n=read(fileno(stdin), buffer, 256)) > 0)
{
buffer[n] ='\0';
if(buffer[n] = '\n') break;
write(input, buffer, strlen(buffer));
}
So I am not sure how to make this loop stop at the press of enter (end of line) so that’s why I have the break code, though I don’t know if that’s done correctly.
The whole objective I am trying to accomplish is to put the input from stdin into the pointer ‘input’
(I am really bad at understanding pointers so bear with me 🙂 )
My problem is that I am getting segmentation faults when I press enter.
I wish I could use fgets because then all this would be solved with a simple
input = fgets(buffer, 256, stdin);
Darn homework 🙁
Anyways, if any of you could point me in the right direction, I would really appreciate it. Thank you!
You’re going about it all wrong. Firstly,
writeis a system call that’s used to write to a open file descriptor. Yourinputis nothing like that – a file descriptor is gained by calling theopensyscall first, or referring to one of the always-open files, e.g.stdin,stdoutorstderr. Not to mention that a file descriptor is aninton Linux.Also, you should remember that the assumption of your input on
stdinending with a newline doesn’t have to be right all the time. Your program may receive some content on standard input that doesn’t contain any newlines, for example contents of some file (redirected tostdin), or the input from keyboard may simply end with aCtrl-D(EOF) instead of the “return” key.On top of all that, an uninitialized pointer doesn’t refer to any valid memory. The declaration of
char *inputdoesn’t give you any right to write/read the memory referred to byinputunless you allocate some memory that this pointer will point to first.Copying strings in C is achieved by using functions declared in
<string.h>. They operate on C-strings, e.g. sequences of characters terminated by\0. In this case,read()doesn’t terminate its output by a\0, in which case you’ll want to use thememcpyfunction instead. Why don’t you simply try reading directly intoinput, though? It doesn’t make much sense to read tobufferfirst, simply to copy the data to another chunk of memory later on.Also, the specification of
readstates that it reads up to count bytes from the file descriptor. Which means that if yourbufferis declared aschar[257], then you should callread(stdin,buffer,257), not 256. It would probably also be more suitable to simply declare the buffer as a 256-element array.I hope that I’ve straightened out some stuff for you.