473,587 Members | 2,547 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

File Processing

Hi,
I have a file with the format
//////////
{blkid:= 10000}
dfd dfd
dfdfdfd
dfd dfd
{blkid:= 10001}
dfd fddd
gdfd dd
dfdd
ere
///////

I want to set '{' as a delimiter and read everything between into a
std::string.
I checked out getline but it expects a "size", in my case I dont know
how big
will the buffer be so how should I solve this problem. I have attached
a sample code which compiles but does not give me the string I expect.
Can you help.
Thanks.
Kapil
// semantics_of_da ta.cpp : Defines the entry point for the console
application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
ifstream sample("sample. dat",ios::in);
ifstream outfile("temp.d at",ios::out) ;
char buf[10];
std::string sample_buf;

if(!sample || !outfile)
{
exit(0);
}

while(!sample.e of())
{
sample.getline( const_cast<char *>(temp_buf.c_s tr()),30,'{');
outfile << temp_buf;

}

gets(buf);

return 0;
}
Jul 19 '05 #1
2 6316
Kapil Khosla <kh*********@ya hoo.com> wrote in message
news:91******** *************** ***@posting.goo gle.com...
Hi,
I have a file with the format
//////////
{blkid:= 10000}
dfd dfd
dfdfdfd
dfd dfd
{blkid:= 10001}
dfd fddd
gdfd dd
dfdd
ere
///////

I want to set '{' as a delimiter and read everything between into a
std::string.
I checked out getline but it expects a "size", in my case I dont know
how big
will the buffer be so how should I solve this problem.
Don't use the member function 'getline()', use the
'free' function 'getline()' declared by <string>.
This function allows the specification of a delimiter,
and also stores the input directly into a 'std::string'
object, no messing about with arrays.
I have attached
a sample code which compiles
I see at least a few things that I think should prevent it
from compiling. See below.
but does not give me the string I expect.
Can you help.
Thanks.
Kapil
// semantics_of_da ta.cpp : Defines the entry point for the console
application.
//

#include "stdafx.h"
This is a nonstandard, Microsoft-specific header.
Please omit such from code posted here. It's
certainly not necessary for what you're asking about.
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
Eh? More 'Microsoft-isms?'. The language discussed
here is ISO standard C++, for which the *only* allowed
name for the entry-point function is 'main()'.

Also _TCHAR is some platform-specific type, not allowed
by the language definition (unless it resolves to the
C++ type 'char').

Why declare these parameters at all anyway? You're
not using them.
{
ifstream sample("sample. dat",ios::in);
ifstream outfile("temp.d at",ios::out) ;
Note that it's redundant to specifiy 'ios::in'
for type 'ifstream', since that 'mode' is its default.

More important, you're trying to use an 'ifstream'
object for output. Didn't your compiler complain?
char buf[10];
What's this for?
std::string sample_buf;

if(!sample || !outfile)
Why not check the stream states immediately after opening,
instead of creating a couple of objects first?
{
exit(0);
Don't you think it would be more 'polite' to at least
inform the user *why* the program abruptly halts?
}

while(!sample.e of())
You're misusing 'eof()' here. It does *not* return
true until *after* an attempt to read past end of file.
It does not 'predict' that the next read will encounter
end of file.
{
sample.getline( const_cast<char *>(temp_buf.c_s tr()),30,'{');
Wow, what malicious abuse of casting!! This is evidence
that one should *really know* what one is doing before
using a cast. 'std::string's member function 'c_str()'
returns an array of *const* characters. Your cast does
*not* change this fact. It's like driving your car
toward a brick wall, and closing your eyes in the belief
that if you don't see it, a collision will not occur.

What you have above is 'undefined behavior'.

Also, there is no 'temp_buf' defined at this scope.
I simply don't believe your above statement that
your code compiles.
outfile << temp_buf;
Again, I see no definition for 'temp_buf'. Also,
you have defined 'outfile' to be type 'ifstream'.
There are no '<<' operators for type 'ifstream'.
This is another statement the compiler should have
diagnosed.

}

gets(buf);
Ack! The Mortal Sin in C and C++ programming. *Never*,
and I mean *never* use 'gets()'. Ever. Pretend it does
not exist. There is absolutely *no way* to use it safely.

Even if there were, you failed to provide its prototype
from <cstdio> or <stdio.h>

By, the way, why are you calling 'gets()' at all? You're
not using what it stores.

If you need to 'freeze' a graphical window containing your
program so it won't 'close', just use:

cin.get();

return 0;
}


Finally, to completely answer your question:

std::getline(sa mple, sample_buf, '{');

Input is stored directly into a 'std::string' object,
no 'size' parameter needed (the 'std::string' will adjust
its size as needed automatically), no dangerous
arrays, no need to abuse casting, and a delimiter
can be specified (defaults to '\n' if not).

If the 'real' code you have does compile, copy
and paste it here, don't retype it, so these
kinds of 'spurious' errors don't waste your time
and ours.

A perusal of the 'C++ FAQ' should help you greatly:
http://www.parashift.com/c++-faq-lite/

-Mike

Jul 19 '05 #2

"Kapil Khosla" <kh*********@ya hoo.com> wrote in message
news:91******** *************** ***@posting.goo gle.com...
Hi,
I have a file with the format
//////////
{blkid:= 10000}
dfd dfd
dfdfdfd
dfd dfd
{blkid:= 10001}
dfd fddd
gdfd dd
dfdd
ere
///////

I want to set '{' as a delimiter and read everything between into a
std::string.
I checked out getline but it expects a "size", in my case I dont know
how big
will the buffer be so how should I solve this problem.


You looked at the wrong getline

getline(my_file , my_string, '}');

john
Jul 19 '05 #3

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

Similar topics

0
2069
by: Sure | last post by:
I my php script I call a perl script that perl script will create a log file From the php script I want to read the log file and write the output to the browser. This operation has to carried out for till the perl script completes the process. This can be identifed by in the log file. My problem is when I read the first line and print...
18
9087
by: Dino | last post by:
dear all, i've created an application for a customer where the customer can upload ..csv-files into a specified ftp-directory. on the server, a php-script, triggered by a cronjob, reads all the data, imports it into a mySQL database and deletes the .csv-file after the import. so far, so good. but in some cases the cronjobs starts...
5
1113
by: matt dittman | last post by:
I have created a windows service that reads emails from a drop directory and moves them to the appropriate mail folder every 15 seconds. I can move, rename and delete the files as needed, up until the CDO.DropDirectory.GetMessages() method is called. At this point, the files are locked until I shut down the service. After processing and...
8
7451
by: Imran | last post by:
hello all, I have to parse a text file and get some value in that. text file content is as follows. ####TEXT FILE CONTENT STARTS HERE ##### /start first 0x1234 AC /end
6
5567
by: Glenn Owens | last post by:
OK I'm on a steep learning curve with XML et.al. and need some advice. I'm writing a B2B front door for a new application. I have multiple data suppliers all sending various formats of flat files. Most of the inbound files are CSV (but a couple are tab-delimitted and one is an Excel spreadsheet). The goal is to read/process/validate each...
5
3118
by: Geoff Pennington | last post by:
My VB.Net app reads an Excel file, processes it one row at a time, and when processing is complete writes the row to a database. The typical file will have several thousand rows and may take a couple minutes to process. I would like to display a running count of the number of rows processed. It is easy enough to keep a counter and set the...
4
2457
by: jesuraj | last post by:
Hi, how can i read input from a data file which contains binary or hex values. I have to use the exact binary data for further processing.only limited number of bits are taken form the file(64 bits) for current processing.Once the processing is done the next 64 bits must be applied.Can this be done?
5
1912
by: B. Williams | last post by:
I need some assistance with random access file processing. I have a function that I would like to change from sequential file processing to random access. Thanks in advance. void updatePower(string filename) { ifstream in(filename.c_str(), ios::in); int cnt = 0; // read all records into database until we reach the end of the file
20
3140
by: Johan | last post by:
How can I include one XML file into another XML file (on the client side, in Firefox)? I think XInclude is just what I need, but Firefox doesn't support it: https://bugzilla.mozilla.org/show_bug.cgi?id=201754 It seems I also can use an "external entity reference", but that depends on a DTD and I'm using XML Schema. Is it also possible...
6
24141
by: ivan.perak | last post by:
Hello, im a beginner in VB.NET... The thing i would like to do is as it follows.... I have a text file (list of names, every name to the next line) which is about 350000 lines long. I would like to split it and create a new file at every lets say 20000 lines... so, the directory output would have to be something like this:
0
7920
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...
0
7849
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...
0
8215
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. ...
1
7973
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...
0
6626
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...
1
5718
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...
0
5394
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...
0
3844
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...
0
3879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.