Dear All
I am beginer to C . I want to read file line by line as string.
I used fgets but how to locate end of line ? Is there any other way ?
Help will be highly appriciated.
Thanks
Dear All
I am beginer to C . I want to read file line by line as string.
I used fgets but how to locate end of line ? Is there any other way ?
Help will be highly appriciated.
Thanks
Read this FAQ entry. Use something like strchr to locate your newline character. If it doesn't show up, you haven't reached the end of the line, and instead have reached the end of your buffer.
Quzah.
Hope is the first step on the road to disappointment.
you could use the fscanf function and just add a newline to that or you could also use fgetc and read while its !='\n'
or if you want to stick with fgets try what quzah said.
Also bear in mind the fact that you'll get both a carriage return AND a linefeed character if the file is open in binary mode ("rb" specified in fopen), and just a linefeed if opened in text mode ("r" specified in fopen).
I would write a simple function to get characters using a while loop, and terminate at eof or end of line. The prototype for such a function could look like this:
where handle is the fopened handle to read from, and outbuf is a pointer to memory allocated before the function call to take the output string. Don't forget to zero-terminate the resultant string.Code:int readfile(FILE *handle, char *outbuf)
Return length of the line read in or -1 for end of file.
I have a question. I've been wondering how does other systems process end-of-line? Do they all put "\r\n" at the end?
It shouldn't matter to your code if you use fopen() in text mode.
Whatever the OS uses, you only see a \n at the end of the line when reading
When writing, you just append a \n, and it gets translated to whatever the OS uses.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
As Salem suggested, this is not entirely accurate. In *nix, there is no "\r" written to text files. In MacOS, IIRC, there is no "\n". They only write one character, not the pair of them. Windows uses both. DOS uses both. And all of the rest of the OSs use whatever they like. The point is, you cannot use the above blanket statement to cover all of the OSs and hope to be correct.Originally Posted by Angoid
Quzah.
Hope is the first step on the road to disappointment.
Point taken .... I was thinking in Windows terms when I posted that rather than *nix as I don't tend to do much C hacking on *nix systems.As Salem suggested, this is not entirely accurate.
My apologies.