473,883 Members | 1,694 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read only last line-

Hello-

I am trying to write a snippet which will open a text file with an
integer on each line. I would like to read the last integer in the
file. I am currently using:
file = fopen("f.txt", "r+");
fseek(file, -2, SEEK_END);
fscanf(file, "%d", &c);
this works fine if the integer is only a single character. When I get
into larger numbers though (e.g. 502) it only reads in the 2. Is there
anything I can do to read the last line as an entity instead of looping
through then entire file? Thanks in advance-

-Ryan

Feb 18 '06
35 11554
Keith Thompson wrote:
Joe Wright <jo********@com cast.net> writes:
[...]
If it's a text file stream and all lines are terminated with '\n'
including the last one, we first trip through the file looking for
'\n' characters and recording the position (offset) of the next
character.

FILE *fp = fopen("file.txt ", "r");
int ch;
long prev = 0, here;
while ((ch = fgetc(fp)) != EOF)
if (ch == '\n') {
prev = here;
here = ftell(fp);
}

At EOF, here is really the end of file and prev is the offset to the
previous (last) line.

fseek(fp, prev, SEEK_SET);

points you to it. Good luck.

That will work (assuming the file is seekable at all), but it requires
reading the entire file, which the OP was trying to avoid.

It records the position of the beginning of the last line, which will
let you re-read from that position, but it assumes that the file isn't
going to change; if you're assuming that, you might as well just read
the entire file and remember the last line.


Good morning Keith. Thank you for reading. Regardless what the OP was
trying to avoid, we must read the entire file. Agreed? Who or what might
change the file while I am reading it? Reading the file character at a
time simplifies things so I don't need to know how long a line is. We
can know how long the last line is by subtracting prev from here,
allocating space for it, backing up (fseek()) to prev and reading the line.

It's a beautiful bright Sunday afternoon in Arlington. Who'sit on the
Left Coast?

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Feb 19 '06 #11
Joe Wright wrote:
[...] Reading the file character at a
time simplifies things so I don't need to know how long a line is. We
can know how long the last line is by subtracting prev from here,
allocating space for it, backing up (fseek()) to prev and reading the line.


7.19.9.4/2: "[...] For a text stream, its file position
indicator contains unspecified information, [...] the difference
between two such return values is not necessarily a meaningful
measure of the number of characters written or read."

So, calculating a line length by subtracting two file
positions is no use. You'd need to count each character of the
line as you read it, starting a new count after each '\n' that
isn't the last character in the file.

--
Eric Sosman
es*****@acm-dot-org.invalid
Feb 19 '06 #12
On 18 Feb 2006 14:33:32 -0800, in comp.lang.c , we******@gmail. com
wrote:
fseek and ftell are really inadequate
functions as they assume file sizes are always less than LONG_MAX which
doesn't make any sense on modern file systems. Many systems have 64
bit versions of these functions which makes a little more sense, but in
about 30 years we're going to wish people were just using intmax_t.

Anyhow, if we ignore that problem, and the other bizarre ANSI-ism that
you can't seek to some offset you haven't previously visited,


Y'know, your advice would be considerably more useful if you skipped
the pointless diatribe at the start and just got right into answering
the question. If you don't like C, why do you hang around here?

Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Feb 19 '06 #13
we******@gmail. com wrote:
[...]
Anyhow, if we ignore that problem, and the other bizarre ANSI-ism that
you can't seek to some offset you haven't previously visited
[... in a text stream ...]


Lots of people (including some who ought to know better)
are seduced by the notion that one can do arithmetic on the
"file position indicators" of text streams. In Standard C,
this is not reliable and leads to undefined behavior.

Some people who have learned the above profess that
Standard C is to blame for this sad situation. Such people
have had but limited experience of different systems' notions
of "file," and would do well to refrain from insulting those
whose knowledge is greater. It is better to remain silent and
risk suspicion of folly than to open one's mouth and confirm it.

Then again, there's always the faint possibility that the
Young Turks have a better idea than the Old Fogeys. If so,
let's hear about the better idea -- but let's hear about it
without gratuitous insults. We stand on the shoulders of
giants; let us refrain from making horsefly-buzzings in their
ears lest they become annoyed and swat us.

--
Eric Sosman
es*****@acm-dot-org.invalid
Feb 20 '06 #14
Eric Sosman wrote:
we******@gmail. com wrote:
[...]
Anyhow, if we ignore that problem, and the other bizarre ANSI-ism that
you can't seek to some offset you haven't previously visited
> [... in a text stream ...]
Lots of people (including some who ought to know better)
are seduced by the notion that one can do arithmetic on the
"file position indicators" of text streams. In Standard C,
this is not reliable and leads to undefined behavior.

Some people who have learned the above profess that
Standard C is to blame for this sad situation. Such people
have had but limited experience of different systems' notions
of "file," and would do well to refrain from insulting those
whose knowledge is greater. It is better to remain silent and
risk suspicion of folly than to open one's mouth and confirm it.


ANSI C contains two functions which satisfy this: fgetpos(), and
fsetpos(). Notice how they used a data type (fpos_t) that does not
imply any arithmetic capabilities?

So you're saying people who see fseek/ftell which clearly uses "long
int" as the file position are not natually supposed to assume they can
do file pointer arithmetic, especially in light of the knowledge that
functions with more restrictive semantics exist as seperate functions?

I am well aware of systems that have a hard time with byte by byte file
offsets. One such obscure system is Windows 98. The difference is,
rather than simply punting and implementing some obscure kind of fseek,
they bit the bullet and did the obvious, but very slow, implementation
that at least behaved consistently.
Then again, there's always the faint possibility that the
Young Turks have a better idea than the Old Fogeys. If so,
let's hear about the better idea
Oh it may surprise you. The first thing I would start with is to stop
idolizing the original creators and/or the C standard, and recognize
when mistakes have been made.

You want an improvement? Not a problem:

#include <stdio.h>
#include <stdint.h>
int fseekB (FILE * fp, intmax_t offs);

The value offs is always taken as an offset (in bytes) from the
beginning of the file, if the offset does not refer to a valid file
position, -1 is returned and errno is set. No value of offs can lead
to UB so long as fp is a valid and active file.

#include <stdio.h>
#include <stdint.h>
intmax_t ftellB (FILE * fp);

The value returned is the exact offset in the file where the
corresponding to the next byte to be read/written. For a valid
non-empty file pointer fp, fseekB (fp, ftellB (fp)) is basically a
NO-OP. At EOF, the position returned is the length of the file. The
function properly observes ungetc(), and all other or ordinary file
operations.

These functions can retain the property of UB, that the ANSI C
committee cherishes so much, if fp is not a valid open file.
Personally, I would prefer that errors be returned if fp is either NULL
or a *closed* fp.

What could be simpler?

If a system has problems implementing it, then that's too bad. The x86
and 68K world implemented entire floating point emulators just to be
compliant with the C standard, a little work on the part of others
won't kill them. And as Microsoft and others have demonstrated -- its
not actually an impractical thing to implement.

If that doesn't work for you, then point me out one system where 1) it
would be impractical to implement this, and 2) which has a working C99
compiler on it. The marginal platforms are not going to be updated
beyond C89 anyways, so there is little sense in making provisions for
them.
-- but let's hear about it
without gratuitous insults. We stand on the shoulders of
giants; [...]


Its hard to *stand* if you are grovelling all the time.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Feb 20 '06 #15
we******@gmail. com wrote:
Eric Sosman wrote:
.... snip ...
-- but let's hear about it without gratuitous insults. We stand
on the shoulders of giants; [...]


Its hard to *stand* if you are grovelling all the time.


When I was 15 I was amazed at the ignorance of my parents. When I
was 25 I was amazed how much they had learned in the past 10
years. You are, apparently, about 15.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Feb 20 '06 #16
On 19 Feb 2006 21:20:00 -0800, in comp.lang.c , we******@gmail. com
wrote:
No value of offs can lead
to UB so long as fp is a valid and active file.
pipes too?
The value returned is the exact offset in the file where the
correspondin g to the next byte to be read/written.
and you've tested this for sparse files, databases, etc? Files with
multiple read/write operations permitted? Files with lockable
sections?
These functions can retain the property of UB, that the ANSI C
committee cherishes so much,
Remarks like this merely make you look like a dickhead.
If a system has problems implementing it, then that's too bad.


Good plan, reduce the portability of C
<flame bait>?
to suit your own apparent inability to programme safely.
</bait>
-- but let's hear about it
without gratuitous insults. We stand on the shoulders of
giants; [...]


Its hard to *stand* if you are grovelling all the time.


And how about when you're so far up yourself that you haven't seen
daylight in weeks?
Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Feb 22 '06 #17
On 19 Feb 2006 21:20:00 -0800, in comp.lang.c , we******@gmail. com
wrote:
The first thing I would start with is to stop
idolizing the original creators and/or the C standard, and recognize
when mistakes have been made.


You again equate "mistake" with compromise, portability and consensus.
Of course, if C owned by one designer that person could do whatever
they liked, eliminating any inconvenient platform or feature along the
way. But its not. Its owned by a committee representing a wide range
of interests, and therefore has to reflect a wider consensus than your
narrow view.

Unfortunately yet again any contribution you might have had to make to
this group is marred by your bias.
Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Feb 22 '06 #18
On 2006-02-22, Mark McIntyre <ma**********@s pamcop.net> wrote:
On 19 Feb 2006 21:20:00 -0800, in comp.lang.c , we******@gmail. com
wrote:
No value of offs can lead
to UB so long as fp is a valid and active file.


pipes too?


A "request that cannot be satisfied" results in a nonzero return, not
UB. It is arguable that this also applies to a call of fseek on a text
stream with a value that does not correspond to a position in the file
which ftell might have returned.
The value returned is the exact offset in the file where the
correspondi ng to the next byte to be read/written.


and you've tested this for sparse files, databases, etc? Files with
multiple read/write operations permitted? Files with lockable
sections?


Again, failure is not the same as UB. What is a specific case that you
think invokes UB?
Feb 22 '06 #19


Jordan Abel wrote On 02/22/06 14:37,:
On 2006-02-22, Mark McIntyre <ma**********@s pamcop.net> wrote:
On 19 Feb 2006 21:20:00 -0800, in comp.lang.c , we******@gmail. com
wrote:

No value of offs can lead
to UB so long as fp is a valid and active file.


pipes too?

A "request that cannot be satisfied" results in a nonzero return, not
UB. It is arguable that this also applies to a call of fseek on a text
stream with a value that does not correspond to a position in the file
which ftell might have returned.

The value returned is the exact offset in the file where the
correspondin g to the next byte to be read/written.


and you've tested this for sparse files, databases, etc? Files with
multiple read/write operations permitted? Files with lockable
sections?

Again, failure is not the same as UB. What is a specific case that you
think invokes UB?


Keep in mind that we're speaking of text streams, where
the number of characters written to a stream need not be the
same as the number of bytes written to the file. A familiar
example is putc('\n', stream) on Windows, where one character
generates two bytes. There are also systems where writing a
newline produces no bytes in the file, systems where a file
contains both data bytes and metadata bytes, and systems that
use state-dependent encodings for extended character sets.

It's not so much a problem of U.B., but of failure that
doesn't produce a reliable indication. Seek to a position
that happens to be in the middle of a multi-byte character
or in the middle of a stretch of metadata, and the problem
may be difficult to detect: a byte in a file does not always
stand alone, but may require prior context (at an arbitrary
separation) for proper interpretation. Here's the stuff of
a nightmare or two: Imagine opening a stream for update,
seeking to the middle of a stretch of metadata, successfully
writing "Hello, world!" there, and only later discovering
that the successful write has corrupted the file structure
and made the entire tail end unreadable ...

It would be nice if one could do meaningful arithmetic on
file position indicators in text streams, but given the rich
variety of file encodings that exist in the world it is not
always possible to do so. The C Standard recognizes this
difficulty, and so does not attempt to guarantee that seeking
to arbitrary positions in text files will work as desired.
The Standard is cognizant of imperfections in reality, and
does not insist that reality rearrange itself for the Standard's
convenience.

--
Er*********@sun .com

Feb 22 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1109
by: Anthony Liu | last post by:
Normally when we do line = in_file_obj.readline() we read from the first line of a file. I am wondering if it is possible to start reading from the last line of file, and then the last but one up to the first line.
4
10328
by: Charles Erwin | last post by:
Is there any way, upon scanning in a file line by line to avoid missing the last line if there is not a newline character (aka you have to hit return on the last line of input in your file). I was sure that there was a way around it but it escapes me if there is one. Thanks Charles Erwin
2
34067
by: Tarren | last post by:
Hi: I want to check my text file to ensure the last line has only DONE on it, prior to loading the file. How can I do this with a StreamReader object to go to the last line so I can perform the string comparison? Thanks
2
3831
by: Eric Lilja | last post by:
Hello, I'm writing a simple program that upon start-up needs to open a text file and read a value on the last line. Then all other accesses to the file will be writes (at the end of it). I'm having two problems with this...I tried opening the file for both writing and reading with: std::fstream file("budget.txt", std::ios_base::in | std::ios_base::out | std::ios_base::app); if(!file) std::cerr << "Error opening file!" << std::endl;
7
25968
by: DemonWasp | last post by:
I've been having some trouble getting the Scanner class to operate the way I'd like. I'm doing some fairly basic file IO and I can't seem to get the class to load the last line/token any way I try. First, I tried using the following: File InFile=new File("input.txt"); Scanner In=new Scanner(InFile);
6
5794
by: magix | last post by:
Hi, when I read entries in file i.e text file, how can I determine the first line and the last line ? I know the first line of entry can be filtered using counter, but how about the last line of entry in EOF while loop ? while (! file.eof() ) { ....
3
1904
by: CCLeasing | last post by:
Hi i'm trying to check if the last line in a file is equal to a string i'm comparing it with. I have the general idea of what I should be doing. Could someone take a look at the following and comment it or suggest improvements. As code it doesn't work at the moment but I hope from it you can see what i'm trying to do. private bool checkduplicates(string filepath, string linetocheck) {
0
2002
by: rahulsapra | last post by:
hello everyone m new to j2me plzz help I have a text file that contains data line by line.. format is : response:<some text><space>Pin:<some text><space>time:<hh:mm:ss> eg response:invalid pin Pin:1111 time:04:04:16
0
1080
by: saral v | last post by:
I need to read the last line in a file from an ftp server without downloading it using ftp streaming. Is there an equivalent command for StreamReader.BaseStream.Seek(offset, origin) in C#? This works only if I download the file.
0
9933
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9781
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11123
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10836
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10407
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9567
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7114
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5982
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4211
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.