473,543 Members | 2,497 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,Beaconif y,nodeId,direct ory);
gNodeVector.pus h_back(*nodeCre ator);
//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.siz e()-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+"b eacon_"+id+".ou t";
outFile = fopen(outputFil eName.c_str(), "w+");
}
else{
myState =e_phase1Node;
outputFileName = outDirectory+"n ode_"+id+".out" ;
outFile = fopen(outputFil eName.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 1690
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,Beaconif y,nodeId,direct ory);
gNodeVector.pus h_back(*nodeCre ator);
//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.pus h_back(cNode(lo cation,skew,
offset,Beaconif y,nodeId,direct ory));

instead of that 'new/delete'?

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

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

gNodeVector.bac k().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+"b eacon_"+id+".ou t";
outFile = fopen(outputFil eName.c_str(), "w+");
}
else{
myState =e_phase1Node;
outputFileName = outDirectory+"n ode_"+id+".out" ;
outFile = fopen(outputFil eName.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.ed u> wrote,
nodeCreator = new cNode(location, skew, offset,Beaconif y,nodeId,direct ory);
gNodeVector.pus h_back(*nodeCre ator);
//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.pus h_back(
cNode(location, skew, offset,Beaconif y,nodeId,direct ory));
Then I call an initNode function for the recently added node *in* the
vector:

gNodeVector[gNodeVector.siz e()-1].initNode();//initialize this new node
formed!!
I would prefer gNodeVector.bac k().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(Coordinat e location, float skew, timeTicks offset, bool Beaconify,
short nodeId, string
directory):outD irectory(direct ory),myClock(sk ew,offset),
myLocation(loca tion), myId(nodeId),is Beacon(Beaconif y){
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(cNod e(location,skew ,offset,Beaconi fy,nodeId,direc tory));
), 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.ed u> wrote in message news:<cn******* ***@gist.usc.ed u>...
[snip]
Here are the constructor and destructore for cNode:

cNode(Coordinat e location, float skew, timeTicks offset, bool Beaconify,
short nodeId, string
directory):outD irectory(direct ory),myClock(sk ew,offset),
myLocation(loca tion), myId(nodeId),is Beacon(Beaconif y){
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::pu sh_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<cNo de>
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.goo gle.com...
"Affan Syed" <as***@usc.ed u> wrote in message
news:<cn******* ***@gist.usc.ed u>...
[snip]
Here are the constructor and destructore for cNode:

cNode(Coordinat e location, float skew, timeTicks offset, bool Beaconify,
short nodeId, string
directory):outD irectory(direct ory),myClock(sk ew,offset),
myLocation(loca tion), myId(nodeId),is Beacon(Beaconif y){
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::pu sh_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<cNo de>
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.ed u> wrote in message news:<cn******* ***@gist.usc.ed u>...
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_p tr<std::ofstrea m>. 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
2742
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 storing products in
2
6350
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 handle, and the actions based on the parsing I can handle, but the simple piece of the puzzle to gather the info as it arrives in the log file is eluding...
303
17433
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. Yahoo store was originally written in Lisp. c. Emacs The issues with these will probably come up, so I might as well mention them myself (which...
6
23560
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
5184
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: Hireability Portability Flexibility The likely candidates seem to be Java, VB.Net, C, C++, C#.
17
2301
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
6113
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 the code please.
54
11912
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 the advantages of smart pointers endlessly (which are currently used in all our C++ software; we use the Boost smart pointers) as I'm seriously...
10
2502
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 in a file seems reasonable. I noticed that the decimal.py module in the standard library has several classes, all of which of course revolve around...
0
7590
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
7347
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
7688
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...
0
5885
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
5271
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
3391
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1817
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
968
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
636
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.