Difference between read() and fgets() in C?

In short, use fgets if you intend to read textual data line by line, use fread elsewhere.

Include char fgets (char * restrict str, int size, FILE * restrict stream) The fgets() function reads at most one less than the number of characters specified by size from the given stream and stores them in the string str. Reading stops when a newline character is found, at end-of-file or error. Reference: fgets() #include ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset); The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf.

The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified. Reference: read().

1 @Andrei for opengroup (and not cplusplus) ... but you can use the POSIX. 1-2008 Reference rather than POSIX. 1-2004 as in your links ;) – pmg Jun 2 at 20:51 updated reference links, @pmg.

Thank you for correcting my answer. – Andrei Sfat Jun 2 at 20:59 @Andrei... based on the above programs I cannot tell the diffrence if I am using fgets to read from stdin or read for reading stdin. Similarly puts(buf) helps me read from stdout through an external program and so does write(stdout,buf).

But read write are slow then puts gets and puts gets work with external java program...could you help clear this – ssD Jun 3 at 1:41 @ssD, how are you calling the c program from java? – Andrei Sfat Jun 3 at 4:37 @Andrei I am using Process.getruntime() and then using BufferedWriter and BufferedReader to read and write in the external C program – ssD Jun 3 at 23:50.

One (read) attempts to read the specified number of bytes, whereas the other (fgets) attempts to read one line and will stop at a newline.

The two functions have nothing in common. Read is a POSIX system call, which reads from a file handle. Fgets is C library function that reads from a FILE *.

I want to read from a stdin stream. Is there any difference in using read() or fgets() to read from the stdin stream. I am attaching the following two pieces of code with fgets and read.

With fgets I can use a java program to write and read from the c program easily. With read and write my java program hangs waiting for the output from C program which does not come. I am just reading a line keeping it in buf and appending A to it.

Java program is able to talk to the following program which works with fgets and puts. Could some one tell the reason.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions