473,320 Members | 1,845 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Why am i getting same file pointers every time

Hi,
I am getting this weird problem. I know what i am doing is strange.. i am
using C++ vectors and fopen, but for some reason if i used ofstream in the
similar scenario it would give me errors.
So here is what i do. I create a new node and insert it in a vecotr as
follows:

nodeCreator = new cNode(location, skew, offset,Beaconify,nodeId,directory);
gNodeVector.push_back(*nodeCreator);
//now lets delete the memory we created for the node
delete nodeCreator;

Then I call an initNode function for the recently added node *in* the
vector:

gNodeVector[gNodeVector.size()-1].initNode();//initialize this new node
formed!!

Inside the initNode function I assign to a class member FILE* outFile
different filenames on the bases of the node id as follows:

void cNode::initNode(){
string outputFileName;
char idBuff[15];

sprintf(idBuff, "%d",myId);

string id(idBuff);

if (isBeacon) {//set the state according to the type of node
myState =e_phase1Beacon;
beaconId= myId;
outputFileName = outDirectory+"beacon_"+id+".out";
outFile = fopen(outputFileName.c_str(), "w+");
}
else{
myState =e_phase1Node;
outputFileName = outDirectory+"node_"+id+".out";
outFile = fopen(outputFileName.c_str(), "w+");
}
fileOpened = true; //this allows me to close the file only if was ever
opened
}

Now the problem that i am getting is that all the output that i do at the
individual nodes (extracted at various time from the vector) goes to the
same file.. and that is the last file created using thre above call. A
little debugging showed the fopen() is returning the *same* file pointer
value for each new file opened. So what is happening makes sense, but WHY is
it returning the same fptr even when i am giving different file names?
I have wasted over a day on this seemingly simple problem (I first was
trying to do with ofstream but that didnt work out either). Do you see any
reason why .. and can any body provide a soln... I would really aprreciate
this !

Best Regards
Affan
Jul 22 '05 #1
6 1676
Affan Syed wrote:
I am getting this weird problem. I know what i am doing is strange.. i am
using C++ vectors and fopen, but for some reason if i used ofstream in the
similar scenario it would give me errors.
So here is what i do. I create a new node and insert it in a vecotr as
follows:

nodeCreator = new cNode(location, skew, offset,Beaconify,nodeId,directory);
gNodeVector.push_back(*nodeCreator);
//now lets delete the memory we created for the node
delete nodeCreator;
Now, this seems like an awful waste of CPU cycles. Why can't you just
write

gNodeVector.push_back(cNode(location,skew,
offset,Beaconify,nodeId,directory));

instead of that 'new/delete'?

Then I call an initNode function for the recently added node *in* the
vector:

gNodeVector[gNodeVector.size()-1].initNode();//initialize this new node
formed!!
Instead of doing size()-1 and indexing, you could just write

gNodeVector.back().initNode();

Inside the initNode function I assign to a class member FILE* outFile
different filenames on the bases of the node id as follows:

void cNode::initNode(){
string outputFileName;
char idBuff[15];

sprintf(idBuff, "%d",myId);

string id(idBuff);
This is extraneous. You could just add 'idBuff' to the string later.

if (isBeacon) {//set the state according to the type of node
myState =e_phase1Beacon;
beaconId= myId;
outputFileName = outDirectory+"beacon_"+id+".out";
outFile = fopen(outputFileName.c_str(), "w+");
}
else{
myState =e_phase1Node;
outputFileName = outDirectory+"node_"+id+".out";
outFile = fopen(outputFileName.c_str(), "w+");
}
fileOpened = true; //this allows me to close the file only if was ever
opened
}

Now the problem that i am getting is that all the output that i do at the
individual nodes (extracted at various time from the vector) goes to the
same file.. and that is the last file created using thre above call.
Have you checked that 'id' is different in every 'initNode' call?
A
little debugging showed the fopen() is returning the *same* file pointer
value for each new file opened.
So? The pointer value is probably just being reused, that's all.
So what is happening makes sense, but WHY is
it returning the same fptr even when i am giving different file names?
Do you keep all the files open or do you close them at some point?
I have wasted over a day on this seemingly simple problem (I first was
trying to do with ofstream but that didnt work out either). Do you see any
reason why .. and can any body provide a soln... I would really aprreciate
this !


Not enough information to give any specific answer, sorry. All I can
suggest at this point is to debug it thoroughly.

V
Jul 22 '05 #2
On Thu, 18 Nov 2004 11:53:13 -0800 in comp.lang.c++, "Affan Syed"
<as***@usc.edu> wrote,
nodeCreator = new cNode(location, skew, offset,Beaconify,nodeId,directory);
gNodeVector.push_back(*nodeCreator);
//now lets delete the memory we created for the node
delete nodeCreator;
1. You know, of course, that your cNode copy constructor and
assignment operator must be correct for this to work.

2. Unless there is something you haven't shown, the 'new' and
'delete' there are gratuitous and should be eliminated.

gNodeVector.push_back(
cNode(location, skew, offset,Beaconify,nodeId,directory));
Then I call an initNode function for the recently added node *in* the
vector:

gNodeVector[gNodeVector.size()-1].initNode();//initialize this new node
formed!!
I would prefer gNodeVector.back().initNode();
Now the problem that i am getting is that all the output that i do at the
individual nodes (extracted at various time from the vector) goes to the
same file.. and that is the last file created using thre above call. A
little debugging showed the fopen() is returning the *same* file pointer
value for each new file opened.


This suggests to me that the files are getting closed prematurely.
It is reasonable for fopen to reuse memory if the files have been
closed.

Or perhaps you are somehow in fact losing the file pointers except
for the last one. Post more complete code - at least the
constructors, assignment operator, and destructor of class cNode.

Jul 22 '05 #3
First of all i appreciate your reply...
1. You know, of course, that your cNode copy constructor and
assignment operator must be correct for this to work. I am using defaults for both, but since my only pointer (that needs more
than a shallow copy) is the FILE* outFile, and I take care of it by
initializing it in a separate call .. hence the initNode() func. I control
the closing of file only if it was opened ( so i think this should cover all
scenarios?).

Here are the constructor and destructore for cNode:

cNode(Coordinate location, float skew, timeTicks offset, bool Beaconify,
short nodeId, string
directory):outDirectory(directory),myClock(skew,of fset),
myLocation(location), myId(nodeId),isBeacon(Beaconify){
fileOpened = false;
};
~cNode(){
if (fileOpened) {
fclose(outFile);
}

};
This suggests to me that the files are getting closed prematurely.
It is reasonable for fopen to reuse memory if the files have been
closed.

hmmm... but i am closing the file only when the destructor gets called. I
did further debuggin and i observe the following:
When i add the second node to the gnodeVector (I am now doing what you
suggested
i.e.gNodeVector.push_back(cNode(location,skew,offs et,Beaconify,nodeId,directory));
), then the following things happen in order

1. A call to constructor of cNode is placed with a *new* id (say first one
way 1 and second one has id 2).
2. Then we have the call to the push_back() of vector and
3. before we get out of the above line I hit my break point in the
destructor of the cNode where it is closing a node with exactly the same
values (including the opened FILE*) and hence closes the file.

..So yes the file does get closed, but i still have *another* (I have no idea
how) inside the vector that i can search and use later. It seems that there
is some interaction with the vector push_back() that i cannot fathom and
solve.

Looking forward to some thing enlightening.
Regards
Affan
Jul 22 '05 #4
"Affan Syed" <as***@usc.edu> wrote in message news:<cn**********@gist.usc.edu>...
[snip]
Here are the constructor and destructore for cNode:

cNode(Coordinate location, float skew, timeTicks offset, bool Beaconify,
short nodeId, string
directory):outDirectory(directory),myClock(skew,of fset),
myLocation(location), myId(nodeId),isBeacon(Beaconify){
fileOpened = false;
};
~cNode(){
if (fileOpened) {
fclose(outFile);
}

};
[snip] hmmm... but i am closing the file only when the destructor gets called. [snip] .So yes the file does get closed, but i still have *another* (I have no idea
how) inside the vector that i can search and use later.
Yes, but that file is closed.
It seems that there
is some interaction with the vector push_back() that i cannot fathom and
solve.
std::vector::push_back() uses the copy constructor, i.e.
cNode::outFile is always closed after the function returns.

Define a copy constructor and assignment operator for cNode
and provide debug messages from all constructors, destructors and
assignment operators. You'll learn a lot from the output!

You had some reason not to open the output file
in the constructor of cNode. Similarly you should provide
a function to close the file.
Alternatively use can std::list<cNode> instead of std::vector<cNode>
and call cNode::initNode after the push back.

Looking forward to some thing enlightening.
Regards
Affan


regards,
Stephan Brönnimann
br****@osb-systems.com
Open source rating and billing engine for communication networks.
Jul 22 '05 #5
Thanks... I did just that.. i.e. provided a closeFile func called at the
end... although this solves the problem, but i still cant understand why i
get a destrctor to the last cNode (replicated) entered when i insert a new
node node into the vector???

Affan
"Stephan Br?nnimann" <br****@hotmail.com> wrote in message
news:d1**************************@posting.google.c om...
"Affan Syed" <as***@usc.edu> wrote in message
news:<cn**********@gist.usc.edu>...
[snip]
Here are the constructor and destructore for cNode:

cNode(Coordinate location, float skew, timeTicks offset, bool Beaconify,
short nodeId, string
directory):outDirectory(directory),myClock(skew,of fset),
myLocation(location), myId(nodeId),isBeacon(Beaconify){
fileOpened = false;
};
~cNode(){
if (fileOpened) {
fclose(outFile);
}

};

[snip]
hmmm... but i am closing the file only when the destructor gets called.

[snip]
.So yes the file does get closed, but i still have *another* (I have no
idea
how) inside the vector that i can search and use later.


Yes, but that file is closed.
It seems that there
is some interaction with the vector push_back() that i cannot fathom and
solve.


std::vector::push_back() uses the copy constructor, i.e.
cNode::outFile is always closed after the function returns.

Define a copy constructor and assignment operator for cNode
and provide debug messages from all constructors, destructors and
assignment operators. You'll learn a lot from the output!

You had some reason not to open the output file
in the constructor of cNode. Similarly you should provide
a function to close the file.
Alternatively use can std::list<cNode> instead of std::vector<cNode>
and call cNode::initNode after the push back.

Looking forward to some thing enlightening.
Regards
Affan


regards,
Stephan Brönnimann
br****@osb-systems.com
Open source rating and billing engine for communication networks.

Jul 22 '05 #6
"Affan Syed" <as***@usc.edu> wrote in message news:<cn**********@gist.usc.edu>...
Thanks... I did just that.. i.e. provided a closeFile func called at the
end... although this solves the problem, but i still cant understand why i
get a destrctor to the last cNode (replicated) entered when i insert a new
node node into the vector???


That is probably a bad idea. Your closeFile really should be in the
destructor. However, you have to realise what happens with object
lifetimes.

In particular, you have to be aware that a compiler may create
temporary copies of your class. These copies will be destroyed when
the compiler is done with them.

Common cases where the compiler inserts these copies:
* when calling a function, arguments may be copied
* when growing a vector, elements may be copied
* when initializing objects with expression of another type.

Now, if you have a file class, which always closes the file in
the dtor, you will have a problem. When the compiler makes a
copy, the destructor will close the file even though there still
is a copy of the FILE*.

The fact that you couldn't use ofstream is telling. ofstream has
the same problem, and "solves" it by preventing ofstream copies.
Apparently, you did try to copy the file. That is precisely why
sterams are better. Instead of a runtime bug, you had a compile
time bug.

Luckily, there is an easy solution. Download boost (www.boost.org)
and use a boost::shared_ptr<std::ofstream>. It will close the file
only when the _last_ shared_ptr to that file is destroyed.

HTH,
Michiel Salter
Jul 22 '05 #7

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

Similar topics

4
by: PHPkemon | last post by:
Hi there, A few weeks ago I made a post and got an answer which seemed very logical. Here's part of the post: PHPkemon wrote: > I think I've figured out how to do the main things like...
2
by: USENETSERVER | last post by:
This seems to be a difficult concept, I am having a heck of a time finding information on techniques for simply having a VB app essentially tail and parse what it finds. The parsing I can...
303
by: mike420 | last post by:
In the context of LATEX, some Pythonista asked what the big successes of Lisp were. I think there were at least three *big* successes. a. orbitz.com web site uses Lisp for algorithms, etc. b....
6
by: Sebastian Kemi | last post by:
How should a write a class to a file? Would this example work: object *myobject = 0; tfile.write(reinterpret_cast<char *>(myobject), sizeof(*object)); / sebek
80
by: Bibby | last post by:
Hi, I'm interested in getting started in the programming world. I've dabbled in C, C++ and VB6. Which would be the best language to focus my attention to regarding the following considerations: ...
17
by: Joe Laughlin | last post by:
I've not used C much before, so I don't know how robust or good this code is. I'd appreciate any feedback or criticisms anyone has! Thanks, Joe #include <stdio.h> #include <string.h>
24
by: rudranee | last post by:
hi there, can anyone tell me how to lines from a file which are odd numbered i.e. 1st,3rd,5th...lines. i tried incrementing file pointer by 2 (fp=fp+2) but it does'nt work Can someone give me...
54
by: Boris | last post by:
I had a 3 hours meeting today with some fellow programmers that are partly not convinced about using smart pointers in C++. Their main concern is a possible performance impact. I've been explaining...
10
by: HCB | last post by:
Hello: The book "Code Complete" recommends that you put only one class in a source file, which seems a bit extreme for me. It seems that many classes are small, so that putting several of them...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.