473,545 Members | 1,745 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fstream & parameters...

Hi,

I was just wondering if someone would like to comment on these two issues.
I had a 15 minute wander around some sites and was curious about loading
files (plain ASCII I think will do for a beginner right now). So I looked
into the fstream library file.
I saved 5 lines to the file:

testing, testing
this is
a
test... 1
2, 3...

And used a while loop (using is.good() ) to load the file using the
getline(is, string) function, like so:

#include <iostream>
#include <stdlib.h>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
ifstream is;
is.open("test.t xt");
string sline;
while(is.good() ){
getline(is, sline);
cout << sline << endl;
}
return 0;
}

Now is there any errors in this at all (apart from the obvious lack of
is.close())? I'm refering mainly to the method, remembering the VB6
lineinput(#) and the way it wasn't exactly a line, especially on binary
files...
Please comment on any bad form I've used above, as I have only started...
Are there better way's at loading files? Anything would be helpful.

Another thing I looked into was the passed argv*[] parameter, which I
(correctly) guessed to be the passed parameter's at run-time (is that term
correct?)... This I would really like someone to clarify for me.
I experimented, and knew that assigning a char pointer to a string like so:
char *test = "testing... ";
string stest = test;
would work... I'm guessing the char *test is a pointer to a character array
(effectively?) and so the assignment of "testing... " get's put into that
char array.
The string see's this pointer to that array and so loads that.

So then I experimented with the *argv[], and noticed that:
string stest = *argv; prodeuced the first parameter passed - but that was
all. Next was:
string stest = argv; which didn't compile (I go by experimentation ) so next
was:
string stest = *argv[1]; which produced the first letter of the first
parameter... And so:
string stest = argv[1]; is the first parameter again, and [2] is the second
(and [n] is the nth)...
Now let me try to understand this one.
string stest = *argv is a pointer to the start of the array... so it
defaults the the 'first' array and so get's the first parameter.
string stest = argv[1] is also a pointer - but this time referencing to the
first array of strings - but it's a reference to the whole array instead of
the starting place?
string stest = *argv[1] is a pointer to the starting place of the array -
therefore the first character.... Just as if I put *test in the other string
example above.

So therefore argv is a pointer to a list of pointers to char arrays? Is that
right?
I do find pointers a tad bit confusing as I'm just getting into them, so I'm
trying to understand them as best as I can early on.

Any feed back will be extremely helpful.
I thank you for reading this post.

--
=========
Comp Whizz
=========
(From The Server-Side)
Jul 22 '05 #1
7 2858
Computer Whizz wrote:
And used a while loop (using is.good() ) to load the file using the
getline(is, string) function, like so: while(is.good() ){
getline(is, sline);
cout << sline << endl;
}
This would apparently read the last line twice although it actually
does
not: you should always test the stream *after* you have tried to read
something. Prior to the attempt to read something, the stream cannot
know what you will attempt next and thus cannot tell reliably whether
it will succeed. It can only tell that it will fail in some situations,
e.g. if a prior attempt to read something failed. You should write the
above loops as:

| for (std::string sline; std::getline(is , sline; )
| std::cout << sline << "\n";
Another thing I looked into was the passed argv*[] parameter, which I (correctly) guessed to be the passed parameter's at run-time (is that term correct?)... This I would really like someone to clarify for me.


You should *read* a tutorial rather than experimenting! Experimenting
might give you a working knowledge of Basic, it won't give you what you
need to know to use C++! C++ is a powerful tool which you better know
how to use correctly to avoid serious damage. It is much like operating
with a chainsaw.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

Jul 22 '05 #2
On Mon, 6 Dec 2004 08:45:04 -0000, "Computer Whizz"
<ol*********@ho tmail.com> wrote:
Hi,

I was just wondering if someone would like to comment on these two issues.
I had a 15 minute wander around some sites and was curious about loading
files (plain ASCII I think will do for a beginner right now). So I looked
into the fstream library file.
I saved 5 lines to the file:

testing, testing
this is
a
test... 1
2, 3...

And used a while loop (using is.good() ) to load the file using the
getline(is, string) function, like so:

#include <iostream>
#include <stdlib.h>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
ifstream is;
is.open("test.t xt");
string sline;
while(is.good() ){
getline(is, sline);
cout << sline << endl;
}
That's wrong, since it doesn't check whether the getline call worked.
Instead, you should do:

while(getline(i s, sline))
{
cout << sline << '\n';
}

if (!is.eof)
{
//something bad happened.
}
return 0;
}

Now is there any errors in this at all (apart from the obvious lack of
is.close())?
The stream is closed (and flushed) automatically on destruction.

I'm refering mainly to the method, remembering the VB6lineinput(#) and the way it wasn't exactly a line, especially on binary
files...
Please comment on any bad form I've used above, as I have only started...
Are there better way's at loading files? Anything would be helpful.
That depends on what you are doing with the file. If you want to
process it a line at a time, then the above is the best way to do it.
If you just want to load the file into a string, there are other ways.
Another thing I looked into was the passed argv*[] parameter, which I
(correctly) guessed to be the passed parameter's at run-time (is that term
correct?)... This I would really like someone to clarify for me.
I experimented, and knew that assigning a char pointer to a string like so:
char *test = "testing... ";
string stest = test;
would work... I'm guessing the char *test is a pointer to a character array
(effectively ?) and so the assignment of "testing... " get's put into that
char array.
"test" above is just a pointer, so you are simply assigning that
pointer to point to the start of the string literal "testing... ".
String literals are held in the program's code, and are valid for the
duration of a program. However, since modifying string literals gives
undefined behaviour, you should instead do:

char const* test = "testing... ";
The string see's this pointer to that array and so loads that.
std::string has a constructor that takes a pointer to a null
terminated char array, and this constructor basically follows that
pointer and loads the std::string with the characters pointed to, up
to the first '\0' character.
So then I experimented with the *argv[], and noticed that:
string stest = *argv; prodeuced the first parameter passed - but that was
all. Next was:
string stest = argv; which didn't compile (I go by experimentation ) so next
was:
string stest = *argv[1]; which produced the first letter of the first
parameter... And so:
string stest = argv[1]; is the first parameter again, and [2] is the second
(and [n] is the nth)...
Now let me try to understand this one.
string stest = *argv is a pointer to the start of the array... so it
defaults the the 'first' array and so get's the first parameter.
*argv is just a dereference of argv. argv is a pointer to a pointer to
char. Dereferencing it gives a pointer to char, and argv is set up so
that this points to a null-terminated string. You could also have
written:

string stest = argv[0];

(remember, a[n] == *(a + n))
string stest = argv[1] is also a pointer - but this time referencing to the
first array of strings - but it's a reference to the whole array instead of
the starting place?
argv[1] references the *second* array - remember that we index from 0.

Argv is set up like this (with a -> representing what a pointer is
pointing to). The array is contiguous - the pointer element1 lies
directly after element0 in memory.
argv (type=char**)->
element0 (type=char*)->"Name of the program"
element1 (type=char*)->"First command line arg"
element2 (type=char*)->"Second command line arg"
...

The number of elements is argc.
string stest = *argv[1] is a pointer to the starting place of the array -
therefore the first character.... Just as if I put *test in the other string
example above.
Right. You could also write argv[1][0].

So therefore argv is a pointer to a list of pointers to char arrays? Is that
right?
Right.
I do find pointers a tad bit confusing as I'm just getting into them, so I'm
trying to understand them as best as I can early on.


I think everyone finds them confusing. There are two things to
consider: what your pointer is pointing at (which may be a single
object or an array of objects), and the type of the thing it is
pointing at.

Tom
Jul 22 '05 #3

"Tom Widmer" <to********@hot mail.com> wrote in message
news:9f******** *************** *********@4ax.c om...
On Mon, 6 Dec 2004 08:45:04 -0000, "Computer Whizz"
<ol*********@ho tmail.com> wrote:
That's wrong, since it doesn't check whether the getline call worked.
Instead, you should do:

while(getline(i s, sline))
{
cout << sline << '\n';
}

if (!is.eof)
{
//something bad happened.
}
Thanks very much Tom. I was just taking an example off of a site and
basically experimented a tad. When I find something interesting I like to
find out a little bit to satisfy me until I look into it fully... That while
above did pop into my mind though.
Now is there any errors in this at all (apart from the obvious lack of
is.close()) ?


The stream is closed (and flushed) automatically on destruction.


Ah good. I didn't want to leave the file open like you can do so many times
in VB...
Is there a "channel" that get's set automatically by any chance? I may call
it a channel because I got that from the sinclairQL stuff, but in VB you
would need to find a "freefile" channel and use it. Was wondering if there
are similarities.

That depends on what you are doing with the file. If you want to
process it a line at a time, then the above is the best way to do it.
If you just want to load the file into a string, there are other ways.
I did also look into "string << is;" but that is word-by-word, ignoring all
spaces and newlines - correct?
If I wanted to load them into a vector<string>, for line-by-line purposes,
would the getline() be fine or is there a better way?

I think for binary files etc I'll wait until I read about them.
char *test = "testing... ";
string stest = test;
would work... I'm guessing the char *test is a pointer to a character
array
(effectively? ) and so the assignment of "testing... " get's put into that
char array.
"test" above is just a pointer, so you are simply assigning that
pointer to point to the start of the string literal "testing... ".
String literals are held in the program's code, and are valid for the
duration of a program. However, since modifying string literals gives
undefined behaviour, you should instead do:

char const* test = "testing... ";


I wasn't planning on madifying it at all really, and usually I use
std::strings as they are much nicer to work with.
The string see's this pointer to that array and so loads that.
std::string has a constructor that takes a pointer to a null
terminated char array, and this constructor basically follows that
pointer and loads the std::string with the characters pointed to, up
to the first '\0' character.


Thanks. That explains it very well.
So then I experimented with the *argv[], and noticed that:
string stest = *argv; prodeuced the first parameter passed - but that was
all. Next was:
string stest = argv; which didn't compile (I go by experimentation ) so
next
was:
string stest = *argv[1]; which produced the first letter of the first
parameter.. . And so:
string stest = argv[1]; is the first parameter again, and [2] is the
second
(and [n] is the nth)...
Now let me try to understand this one.
string stest = *argv is a pointer to the start of the array... so it
defaults the the 'first' array and so get's the first parameter.
*argv is just a dereference of argv. argv is a pointer to a pointer to
char. Dereferencing it gives a pointer to char, and argv is set up so
that this points to a null-terminated string. You could also have
written:


Ahh, okay. Cheers for the info.

string stest = argv[0];

(remember, a[n] == *(a + n))
string stest = argv[1] is also a pointer - but this time referencing to
the
first array of strings - but it's a reference to the whole array instead
of
the starting place?
argv[1] references the *second* array - remember that we index from 0.


Yes, sorry. I did actually write 0 in code, but was in the middle of
something else which used 1 as the base - long story, basically the 'var[0]'
is turned into 'var'... It's not a "proper" programming language etc, and I
switched over and wrote [1] - my mistake.

Argv is set up like this (with a -> representing what a pointer is
pointing to). The array is contiguous - the pointer element1 lies
directly after element0 in memory.
argv (type=char**)->
element0 (type=char*)->"Name of the program"
element1 (type=char*)->"First command line arg"
element2 (type=char*)->"Second command line arg"
...

The number of elements is argc.
Thank you.That does help make an image in my mind.
string stest = *argv[1] is a pointer to the starting place of the array -
therefore the first character.... Just as if I put *test in the other
string
example above.
Right. You could also write argv[1][0].


Ooo... I guess it is logical - but I wouldn't have guessed that. Thanks
again.

So therefore argv is a pointer to a list of pointers to char arrays? Is
that
right?
Right.


Great.
I do find pointers a tad bit confusing as I'm just getting into them, so
I'm
trying to understand them as best as I can early on.


I think everyone finds them confusing. There are two things to
consider: what your pointer is pointing at (which may be a single
object or an array of objects), and the type of the thing it is
pointing at.

Tom


And with your help I feel like I've started to get the correct grip on them.
Thank you.

--
=========
Comp Whizz
=========
(From The Server-Side)
Jul 22 '05 #4

Computer Whizz wrote:
"Tom Widmer" <to********@hot mail.com> wrote in message
news:9f******** *************** *********@4ax.c om...
On Mon, 6 Dec 2004 08:45:04 -0000, "Computer Whizz"
<ol*********@ho tmail.com> wrote:
Ah good. I didn't want to leave the file open like you can do so many times in VB...
Is there a "channel" that get's set automatically by any chance? I may call it a channel because I got that from the sinclairQL stuff, but in VB you would need to find a "freefile" channel and use it. Was wondering if there are similarities.
Not really. The 'fstream' object you use /is/ what you'd call the
channel.
However, in C++ objects have constructors (aka ctor) and destructors
(dtor)
which work automatically. If you give the fstream ctor a filename, it
will
"open" that file for you. When you stop using it, the dtor will "close"
it.
You can also call the .close( ) member earlier.
I did also look into "string << is;" but that is word-by-word, ignoring all spaces and newlines - correct? Yes.
If I wanted to load them into a vector<string>, for line-by-line purposes, would the getline() be fine or is there a better way?

There are other ways, but this one is very clear. Usually, that is what
we call 'better' but for some programs "fast" is better than "easily
understood". Compare prices for faster CPUs and better developers, and
you'll see why.
BTW. try to figure out what this line does
std::vector<std ::string> args ( argv, argv+argc );
Regards,
Michiel Salters

Jul 22 '05 #5

"Dietmar Kuehl" <di***********@ yahoo.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Computer Whizz wrote:
And used a while loop (using is.good() ) to load the file using the
getline(is, string) function, like so:
while(is.good() ){
getline(is, sline);
cout << sline << endl;
}


This would apparently read the last line twice although it actually
does not: you should always test the stream *after* you have tried to read
something. Prior to the attempt to read something, the stream cannot
know what you will attempt next and thus cannot tell reliably whether
it will succeed. It can only tell that it will fail in some situations,
e.g. if a prior attempt to read something failed. You should write the
above loops as:

| for (std::string sline; std::getline(is , sline; )
| std::cout << sline << "\n";


Ah, thank you. Although I do prefer the while(getline(i s, sline)) {} in
another post.
Another thing I looked into was the passed argv*[] parameter, which I

(correctly) guessed to be the passed parameter's at run-time (is that

term
correct?)... This I would really like someone to clarify for me.


You should *read* a tutorial rather than experimenting! Experimenting
might give you a working knowledge of Basic, it won't give you what you
need to know to use C++! C++ is a powerful tool which you better know
how to use correctly to avoid serious damage. It is much like operating
with a chainsaw.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting


I am currently reading through Advanced C++, and will probably go onto a STL
book (reference or not).
I much prefer examples and a reference on how to use the function, rather
than learning all technical words, which this book seems set on doing...
Don't get me wrong, it get's the point between two people much better, and I
will enevitably learn it - but more through experimentation and adaption.
I do however look up everything as much as I can online though, getting some
background on how to use the function/type correctly. That's why I am doing
things slowly.

I have no intention to compile a program without fully understanding it -
much like I have no intention to wield an active chainsaw without having
prior experience on lighter and inactive models.

--
=========
Comp Whizz
=========
(From The Server-Side)
Jul 22 '05 #6

"msalters" <Mi************ *@logicacmg.com > wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .

There are other ways, but this one is very clear. Usually, that is what
we call 'better' but for some programs "fast" is better than "easily
understood". Compare prices for faster CPUs and better developers, and
you'll see why.
Yep - I will definately get into the speed thing later on - but
understanding it right now is the most important thing.


BTW. try to figure out what this line does
std::vector<std ::string> args ( argv, argv+argc );
Regards,
Michiel Salters


The declaration defines a vector (array in my mind) of strings - 2
dimensional. One with argv and another with argv concatinated with argc?
I'll try it out after work - It'll be interesting to see if I'm right.
Thanks...

--
=========
Comp Whizz
=========
(From The Server-Side)
Jul 22 '05 #7

"Computer Whizz" <ol*********@ho tmail.com> wrote in message
news:cp******** **@newsg1.svr.p ol.co.uk...
BTW. try to figure out what this line does
std::vector<std ::string> args ( argv, argv+argc );
Regards,
Michiel Salters


Just to follow up - I tried it, and after much fiddling I tried to output
the data.... In my round-about ways it led me to research vector's a little
bit and so I found an ( beginning pointer, end pointer ) bit...

So it creates an array of strings, from the starting pointer (argv) to the
ending pointer (argv + argc)...

Thank you very much for the info there...

--
=========
Comp Whizz
=========
(The C++ beginner)
Jul 22 '05 #8

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

Similar topics

6
3190
by: Armando | last post by:
Hallo ! I habe some error in my programm,because i use <fstream.h>,I want to use <fstream> but i don´t know which fonctions i must modify in my program ? Thanks you for your help. Armando.
3
7077
by: Manuel Maria Diaz Gomez | last post by:
Hi everybody, This is probably trivial, but I just can't see it. In the followinf function: /*-------------------------------------------------*/ File::loadFile(string inputFile) /*-------------------------------------------------*/ { ifstream myFile;
16
2436
by: Steven T. Hatton | last post by:
In the following code, the only way I can figure out to pass an array of const is by setting the template argument to const in the instanciation expression. It would be (or seem to me) better if I could set that qualifier in the function call. Can that be done? #include <iostream> using std::ostream; using std::cout;
3
4176
by: kieran | last post by:
Hi, I'm using fstream.get to read in a character from a file, then print it on the screen. I have a file called test.log that contains "Hello, World!", but when I try and print the contents out on the screen I get "Hello, World!!". The following is the code (please ignore all wxWidgets classes): void SystemBackupFrm::compress() { using...
3
4837
by: John Smith | last post by:
I would like to write over a file if it exists (or create one if it doesn't exist). The following codes do nothing if the file already exists. How do I get it to overwrite an existing file? Also, if the existing file is longer than what's going to be written, how do I erase the excess portion of the existing file? fsF.open ("test.txt",...
3
3716
by: John R. Delaney | last post by:
If I try to declare an object of type fstream (or ofstream), I run into a compilation error refering to an __something function or variable. Please note, I am including <fstream>, not <fstream.h>. I do know that much. Thanks in advance for any assistance. John
6
1932
by: Rich | last post by:
Hello, I have to create a table in an Access mdb (remotely) on the fly. Create Table tbl1(fld1 Integer, fld2 varchar(10), fld3...) Then I have to insert data: Insert Into tbl1 Values(" & val1 & ", '" & val2 & "',...")"
9
5273
by: Someonekicked | last post by:
In my program, I need to open multiple files, and I wont know till after the program execution how many of them (user will enter that value). So I am using a vector of fstream. I am using fstream since I will need to write and read from files, and I am using those files as binary files. I made a sample of what's going on (below). Without...
1
5341
by: MForey | last post by:
I'm attempting to create a program that uses fstream objects to read/write to files. However, it is currently balky at best. The fstream.write call doesn't return an error, but the modified data doesn't show in the next read, or when I open the file itself. Additionally, I get a insufficient parameters error from if I remove the ios flags from...
0
7453
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
7390
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
5958
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...
0
4940
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
3441
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
3436
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1865
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
1
1007
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
692
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...

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.