473,797 Members | 3,144 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to read this kind of file?

Hi,

Suppose I a file with the following format --- each line is either a
record or a blank line.

If it is a record, it might be of one of the following format, where
the first format means t equals 1 by default.
w h
w h t

It is very simple to read this file if it only have "w h" record or "w
h t" record. Like the following tow code segments:

ifstream in_file;
int w, h
while(in_file >> w >> h){
....
}

ifstream in_file;
int w, h, t
while(in_file >> w >> h >> t){
....
}

But it is not very straight forward to me how to read a file with both
kinds of records. Would you please help me?

Best wishes,
Peng

Jul 23 '05 #1
6 1339
Pe*******@gmail .com wrote:
Suppose I a file with the following format --- each line is either a
record or a blank line.

If it is a record, it might be of one of the following format, where
the first format means t equals 1 by default.
w h
w h t


step 1: Read the whole line with getline() or fgtes(), respectively.
step 2: Parse the line (and you'll see if it contains 0, 2, or 3
tokens).

Jul 23 '05 #2
Pe*******@gmail .com wrote:
[snip]
But it is not very straight forward to me how to read a file with both
kinds of records. Would you please help me?

Best wishes,
Peng


My preferred method is to roll everything up into a class or struct.
With your example, the result would look something like:

#include <iostream>
#include <string>
#include <sstream>

struct record
{
int w, h, t ;

// Put constructors and other members if you want them.
} ;

std::istream &operator>>(std ::istream &is, record &r)
{
int w, h, t ;
std::string s ;

if (std::getline(i s, s))
{
std::istringstr eam ss(s) ;
if (ss >> w >> h)
{
r.w = w ;
r.h = h ;

if (ss >> t)
r.t = t ;
else
r.t = 1 ;
}
}

return is ;
}

std::ostream &operator<<(std ::ostream &os, const record &r)
{
os << r.w << ' ' << r.h << ' ' << r.t ;
}

Now you can do all sorts of neat stuff. You could read the file like
you were original trying to:

record r ;
while (in_file >> r) { ... }

But you could also easily create a whole vector/list/etc from your file
in one command:

#include <vector>
#include <algorithm>
#include <iterator>
....
std::vector<rec ord> records ;
std::copy(std:: istream_iterato r<record>(in_fi le),
std::istream_it erator<record>( ),
std::back_inser ter(records)) ;
Or my favorite, you could create a function object to process a record,
and then process the whole file with one command:

class process_record
{
public :
void operator()(cons t record &r)
{
// Do some record processing.
std::cout << "I just processed record: "
<< r << std::endl ;
}
} ;

....

std::for_each(s td::istream_ite rator<record>(i n_file),
std::istream_it erator<record>( ),
process_record( )) ;
Anyhow, I hope this at least gives you some ideas of how to approach
your problem. Good luck!

-Alan
Jul 23 '05 #3
Thank you for the detailed example.

Peng

Jul 23 '05 #4
I feel there are several getline functions. Is the following webpage
describe the one that you use?
http://www.cppreference.com/cppio/getline.html

I'm confused why the return value of "istream&" can be used as the
condition. Or do I read the wrong definition?

Best wishes,
Peng

Jul 23 '05 #5
Pe*******@gmail .com wrote:
I feel there are several getline functions. Is the following webpage
describe the one that you use?
http://www.cppreference.com/cppio/getline.html

I'm confused why the return value of "istream&" can be used as the
condition. Or do I read the wrong definition?

Best wishes,
Peng


Yes. That is the one used in my example.

The standard defines two functions named "getline". One is actually a
member function of the basic_istream template class. It let's you do
things along the lines of:

char buffer[1024] ;
cin.getline(buf fer, 1024, '\n') ;

The other, used in the example code in previous posts, is defined as
part of the "Strings library" (clause 21 of the standard). It is
designed specifically to read from a stream into a std::string (or
std::wstring) object. The advantage of this form is that you don't have
to guess at how long a line is. It will keep reading into your string
object (which will keep resizing itself when appropriate) until you've
reached an end of line. The disadvantage, of course, is that you have
to use a string object, which may or may not be appropriate for your
task. For tasks that involve processing lines of text (like the one you
posed) this is usually the easiest approach (in my opinion).

-Alan
Jul 23 '05 #6
Alan Johnson wrote:
Pe*******@gmail .com wrote:
I feel there are several getline functions. Is the following webpage
describe the one that you use?
http://www.cppreference.com/cppio/getline.html

I'm confused why the return value of "istream&" can be used as the
condition. Or do I read the wrong definition?

Best wishes,
Peng


Yes. That is the one used in my example.

The standard defines two functions named "getline". One is actually a
member function of the basic_istream template class. It let's you do
things along the lines of:

char buffer[1024] ;
cin.getline(buf fer, 1024, '\n') ;

The other, used in the example code in previous posts, is defined as
part of the "Strings library" (clause 21 of the standard). It is
designed specifically to read from a stream into a std::string (or
std::wstring) object. The advantage of this form is that you don't have
to guess at how long a line is. It will keep reading into your string
object (which will keep resizing itself when appropriate) until you've
reached an end of line. The disadvantage, of course, is that you have
to use a string object, which may or may not be appropriate for your
task. For tasks that involve processing lines of text (like the one you
posed) this is usually the easiest approach (in my opinion).

-Alan


Sorry, I answered incorrectly. The "getline" documented in the link you
included is the first form I mentioned above. The getline I used in the
example is the second form.

-Alan
Jul 23 '05 #7

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

Similar topics

75
5369
by: Greg McIntyre | last post by:
I have a Python snippet: f = open("blah.txt", "r") while True: c = f.read(1) if c == '': break # EOF # ... work on c Is some way to make this code more compact and simple? It's a bit spaghetti.
2
3093
by: Sandman | last post by:
Just looking for suggestion on how to do this in my Web application. The goal is to keep track of what a user has and hasn't read and present him or her with new material I am currently doing this by aggregating new content from all databases into a single indexed database and then saving a timestamp in the account database (for the current user) that tells me when the user last read items in the aggregated database.
40
61235
by: Abby | last post by:
My .dat file will contain information like below. /////////// First 0x04 0x05 0x06 Second 0x07
14
9138
by: Mark Broadbent | last post by:
Does anybody know what is (factual please -not just guess) the quickest method to read data from a file? I am not interested in the format of the data (i.e. blocks, bytes, string etc) just that the IO to read the data is very quick. I am currently using a Streamreader and have found the readline method to perform slightly better than the read method (although it is nice to have the read's granuality of one byte). Is there any faster reader...
5
7639
by: Mika M | last post by:
Hi! I'm trying to read text file like... "Field1";"Field2";"Field3";"Field4" "ABCD";"EFGH";"1234";"20051020" "AABB";"CCDD";"2468";"20051021" "CCDD";"XXYY";"4321";"20051022" ....using OLE DB-provider. Unfortunately I can't affect in what kind of
5
5120
by: Sumana | last post by:
Hi All, We developed our project on VC++.Net console application to create image of disk and to write the image We are having problem with reading and writing the sector beyond 6GB Disk or Partition we are using ReadFile , WriteFile and setFilePointerEx to read and write the sectors and we are reading/writing 102400 sectors together, even we have reduced the sectors still it is not able to read or write, our program is working fine...
35
11501
by: RyanS09 | last post by:
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
7
2149
by: Tracks | last post by:
I have old legacy code from vb5 where data was written to a file with a variant declaration (this was actually a coding error?)... in vb5 the code was: Dim thisdata as integer Dim thatdata Dim someother as integer thatdata = ubound( Array1 )
9
2258
by: Hollywood | last post by:
Hello members of the comp.lang.c++, My log file is made of a set of 1000 following lines kind: 21/09/07 13:49:56,MW.SET.D_IGLS,2.000000 21/09/07 13:49:56,MW.SET.GNP_NT,7.000000 ..... commas ',' are used as field separators (data, name, value).
70
1059
by: quickcur | last post by:
hi can anyone explain me to read image to memory from a url it is very easy in java but it is hard to find an complete solution in c/c++. Thanks,
0
9685
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...
1
10209
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
10023
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...
1
7560
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6803
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
5459
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4135
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2934
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.