ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I'm still working through "The C programming launguage" by K&R, but also have "Advanced Linux Programming" sitting on my hard drive, I can always use more.
You should have a look at anything written by W Richard Stevens. For starters teh above mentioned, and then the classic Unix Network Programming Vol I after that.
Originally posted by h/w when fgets reads a line, it reads in the '\n' too.
is there a way to use fgets so that it stops reading when it encounters the newline?
thanks.
gets() is bad as theres no way of setting a limit. I have made my own version to solve that problem:
Code:
#include <stdio.h> /* we need this for getchar() and EOF */
int getsn (char * buf, int max)
{
int count, c;
for (count = 0; count < max - 1; count++) /* don't forget to leave one for \0 :D */
{
if ((c = getchar ()) == '\n' || c == EOF)
break;
else
*(buf + count) = c;
}
*(buf + count) = '\0'; /* append the newloine character */
return (c == EOF)?EOF:0;
}
I know what he asked. But fgets reads a new line - always has done which is why I suggested that function which I often use. It can be easily modified to to work with any file by including an extra file stream argument:
Code:
#include <stdio.h> /* we need this for getc() and EOF */
int getsn (char * buf, FILE * pstream, int max)
{
int count, c;
for (count = 0; count < max - 1; count++) /* don't forget to leave one for \0 */
{
if ((c = getc (pstream)) == '\n' || c == EOF)
break;
else
*(buf + count) = c;
}
*(buf + count) = '\0'; /* append the newloine character */
return (c == EOF)?EOF:0;
}
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.