i have one serial file
n1\n2\n2\n4\n5\n6\........n
want to read last file only in above file....can any one tell me how come/

We do not speak gobbledygook. Please explain with a better example and more explanation.

Generally, the only way to read the last item of a text file is to read the entire file.

sup dawg i herd you like to read, so we put some files in your files so you can read while you read

....

naw serosly, what are you saying?? are you saying you want to read the last LINE from your file?

is that it?


.

okay, then you do this:

(1) open the file using "fopen".
(2) use a while loop to read each line into a string buffer using "fgets" until a NULL is returned.
(3) when fgets returns a NULL, it means there are no more lines. the last line read will still be in your string buffer.

"fopen" and "fgets" are widely-used commands from the <stdio.h> standard library. you will find tons of examples on the various online references. here is a good one: http://www.cplusplus.com/reference/clibrary/cstdio/fgets.html

C++ is a superset of C. that website covers C++ and C. the referenced <stdio.h> library is standard C.

hey... wait a minute. if you're the best jew since jc, shouldnt you be omniscient?

i did the same ..error is coming..can u explain me in coding ? plz

i did the same ..error is coming..can u explain me in coding ? plz

Post your code -- we can not see what you wrote. Also post error message.

Post your code -- we can not see what you wrote. Also post error message.

I think he meant he wants us to show him an example... I guess I might as well contribute something to this community. I will assume you want to read text from a .txt file so bare with me as I post my solution for this problem...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char * argv[])
{
    FILE*file = fopen ("input.txt","r");
    
    if (file == NULL)
    {
       /*if no file exists the end program*/
       puts("Error! file input.txt does not exist");
       system("pause");
       return 0;
    }
    
    char string[50];
    char word[50];
    
    char ch = 0;
    /*It appears as though you can use int or char
    Use your better judgement */
    int num = 0;
    
    while (ch != EOF)/*EOF == -1*/
    {
          ch = fgetc(file);
          string[num++] = ch;
          
          if (ch == '\n')
          {
             string[num-1] = '\0';
             strcpy(word,string);
             num = 0;
          }
    }
    printf("%s\n",word);
    system("pause");
}

Nothing fancy but gets the job done. I hope its suitable

using fgets() would make the program a lot simpler. When this loop finished it will have read the last line of the file.

while( fgets( string, sizeof(string), file) )
{
   // do nothing here
}

A.D. is right. "fgets()" is the solution.

I guess I might as well contribute something to this community.

"contributing to the community" does not include doing some slacker's homework assignment for them. by doing so, you're circumventing the community's efforts to discourage laziness and plagiarism.

anyhow, relying on EOF is generally considered a poor way to read text files. it is not consistent across platforms, and you'll eventually get burned.

http://www.gnu.org/software/libtool/manual/libc/EOF-and-Errors.html

if you really feel you must look for the End of File marker, then use "feof()".


.

The documentation you just provided says that it is consistent, but in some cases, EOF can also be used to report errors. So either way, I don't see how you're getting burned. Care to explain? (Are you just saying you can use it to make sure it isn't an error? If so then no explanation needed. The consistency bit could be interpreted differently though)

using a loop such as

while( file.eof() )
{
   
}

will cause problems on the last line -- such a loop will read the last line twice and whatever code you have inside { and } will get executed twice on eof. That's why fgets() works better as loop controller because it returns NULL when eof has reached.

To demonstrate that problem, compile and run the program below

#include <stdio.h>
#pragma warning(disable: 4996)

int main()
{
    FILE* fp = fopen("ReadMe.txt", "r");
    char line[255];
    int counter = 0;
    if( fp != NULL)
    {
        
        while( !feof(fp) )
        {
            counter++;
            fgets(line, sizeof(line), fp);
            printf("%d: %s", counter, line);
        }
        fclose(fp);
    }
}

And below is the output -- notice the last line appears twice (lines 33 and 34 are the same line in the file)

15: Application Wizard.
16:
17: test7.cpp
18: This is the main application source file.
19:
20: ////////////////////////////////////////////////////////////////////////////
/
21: Other standard files:
22:
23: StdAfx.h, StdAfx.cpp
24: These files are used to build a precompiled header (PCH) file
25: named test7.pch and a precompiled types file named StdAfx.obj.
26:
27: ////////////////////////////////////////////////////////////////////////////
/
28: Other notes:
29:
30: AppWizard uses "TODO:" comments to indicate parts of the source code you
31: should add to or customize.
32:
33: ////////////////////////////////////////////////////////////////////////////
/
34: ////////////////////////////////////////////////////////////////////////////
/
Press any key to continue . . .


A.D. is right. "fgets()" is the solution.


"contributing to the community" does not include doing some slacker's homework assignment for them. by doing so, you're circumventing the community's efforts to discourage laziness and plagiarism.

.

I think that your incorrect in saying fgets() is the solution, firstly there are always several ways to approach the same problem. Ive seen you post several times and it seems as though you see programming as something very black and white.

Aside from that I see nothing wrong with looking for the EOF as I did, and this is the reason I found fgets() to not work for the purposes of this particular problem. The reason is because fgets() returns at the end of a line however he wants the last line. From my experience when dealing with the last line of a file two things can happen. You can get a newline character or the EOF. The first time I tried to do with without the EOF this is what happened. I read the last line with text on it, but a space is always a character and as a result it went to the next line which had a space and the "EOF" (it doesn't really have an EOF character but you know what I mean). What Im getting at is that it is possible that the last line can be only a space. Of course I won't say that my solution is all that great either because it doesn't take into account that the string size is only 50.

Lastly, I have a major problem with that way you gets explain things, you guys expect people to know about all kinds of stuff. Not everyone was born at a computer programming in C. Its quite clear that not everyone knows as much as you do which is why you are helping them. At least when you guys help please explain, I'm not telling you to write an expository piece but I think you guys don't explain, it seems to me that you assume that the person your helping is at the same level as you. Just my observation.

C is hard for everyone when they are learning. I'm relearning C, and it is hard for me again. But don't get frustrated with the people trying to help you. You can disagree if you want, but if you need a more simple explanation, ask them to break down whatever you're having trouble with further.

I'm not saying you cant look for the end of file. what i said is this:

if you really feel you must look for the End of File marker, then use "feof()".

as for the EOF macro, it's not standardized. It can have different values depending on compiler. It can also be a catchall for various error codes. or ... not.

eyah, maybe it'll for your application, but if someone thinks that's "consistent", i'd like to see what they consider to be "inconsistent"

Comments
I'm sorry but this is wrong kiddo.

>as for the EOF macro, it's not standardized.
Actually it is.

>It can have different values depending on compiler.
That's why it's a macro. If fgetc encounters the end of the file, it will return the value represented by EOF.

>It can also be a catchall for various error codes. or ... not.
Actually, the standard requires it to be a catchall for any read errors. Which makes it a better option than feof(), unless of course you're also using ferror to check the stream for errors.

No matter how you cut it, the loop

while( !feof(file) )
{
   // blabla
}

will make the program read the last line (fgets()), last character (fgetc()) or last read (fread()) appear to be read twice, as I proved in my previous post. That's why such a loop is poor coding and will cause problems.

No matter how you cut it, the loop

while( !feof(file) )
{
   // blabla
}

will make the program read the last line (fgets()), last character (fgetc()) or last read (fread()) appear to be read twice, as I proved in my previous post. That's why such a loop is poor coding and will cause problems.

That's not entirely true:

fgets( buffer, sizeof(buffer), file );
while( !feof(file) )
{
  /* do whatever with buffer here */

  fgets( buffer, sizeof(buffer), file );
}

As long as you only do something with the result of the read operation after you've checked for an EOF, you're fine.

Of course, checking the return value of fgets() is a safer solution since feof() doesn't indicate any errors in the stream, whereas the return value of fgets() does. Which means you'd also need ferror() in the above while() loop condition to ensure that no errors occur... and that results in a functionally equivalent solution to checking the return value of fgets() in the first place, so the long and short of it is that you end up with cleaner code by checking the return value of fgets() and not using feof(). :P

>That's not entirely true
Repeating code unnecessarily, and stubbornly forcing the use of a function that was not designed to be used as it would have been in Pascal/FORTRAN.
No wonder the practice keeps popping up all the time, since people that knows better continue to perpetuate the "possible" use of it.

>>No consensus?
Yes, I'm right and everyone else is wrong :) Its not a matter of majority opinion -- I already explained with example whay feof() doesn't work as a loop control. Take it or leave it.

I'm not going to lie, it is pretty frustrating to see such varying opinions on a topic like this. No consensus?

Rather than looking for consensus, you would be better served by obtaining your own opinion based in practice and understanding how the language works.
Then your confidence will increase, and it will cut through the self-promoted ego BS projected around you.

Comments
well said
Gread advice :)

I'm not going to lie, it is pretty frustrating to see such varying opinions on a topic like this. No consensus?

it's a rare instance around here where you ever find a consensus.

as for using the EOF macro, personally i rarely ever look for the "end-of-file" marker when reading text files, i always parse results using fgets() and check the return value of that function. On the few occasions where i specifically need to look the end-of-file marker, i use the feof() and check the errno result from ferror().

Anecdotally, Ive heard of a number of situations where relying on the EOF macro results in unexpected behavior and problematic code, and I understand that there have been some bugs related to this macro.

at least one authority -- the GNU C Library Manual -- suggests that using EOF macro is not reccommended:

Since EOF is used to report both end of file and random errors, it's often better to use the feof function to check explicitly for end of file and ferror to check for errors.

this corresponds to my experience and anecdotal observations, so I'm content to leave it at that.

I'm not going to argue about it, because it's not a critical issue, but I'm also not going to use the EOF macro either. I'm going to continue to rely on the consistently reliable fgets() function, as I always have.

that's my opinion based on my limited professional experience. You can take it or leave it.


.

>That's not entirely true
Repeating code unnecessarily, and stubbornly forcing the use of a function that was not designed to be used as it would have been in Pascal/FORTRAN.
No wonder the practice keeps popping up all the time, since people that knows better continue to perpetuate the "possible" use of it.

You seem to have misunderstood me. I was not condoning nor recommending the code that I posted; the sole purpose was to help others understand why using feof() in a loop condition is not particularly useful and not blindly follow what Ancient Dragon said (that using feof() automatically causes your program to read the last line twice).

This article has been dead for over six months. Start a new discussion instead.