473,770 Members | 1,677 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

File descriptor turns to 0!

Hi,

I have a very simple prg over here, trying to read the lines of a file

#include <iostream>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main() {

char tempn[100];

char line[40];
fstream f;
sprintf(tempn," %s/%s\0","/root/somedir/prj1/","temp.cfg ");
f.open(tempn,io s::in); // open file for reading
if(!f) {
cout<<"Could not find network.cfg in the directory"; // couldnt open
it
}
while(f.getline (line,10)) {

cout<<" i am in"<<endl;
if(f.eof())
break;
}
}
/* */ cout<<"f "<<f<<endl; //what is the file descpr
f.close();
delete [] tempn;
return 1;
}
when i run this prg and try to read a file of 6 lines, it prints 'i am
in' 6 times but the file descrp. is printed out as 0. While if I print
the value of the file descrp within the loop, it is ok.Why is that
happening?

Thanks

Sidhu
Jul 22 '05 #1
6 1774
Siddharth Taneja wrote:
I have a very simple prg over here, trying to read the lines of a file

#include <iostream>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main() {

char tempn[100];

char line[40];
fstream f;
sprintf(tempn," %s/%s\0","/root/somedir/prj1/","temp.cfg "); ^ ^
You seem to have an extra slash in there, no?



f.open(tempn,io s::in); // open file for reading
if(!f) {
cout<<"Could not find network.cfg in the directory"; // couldnt open
it
Actually the file name seems to be 'temp.cfg', not 'network.cfg', the
error message is misleading.
}
while(f.getline (line,10)) {

cout<<" i am in"<<endl;
if(f.eof())
break;
}
}
/* */ cout<<"f "<<f<<endl; //what is the file descpr
Why are you trying to print 'f'? It's not "file descpr". It's a stream
object. What do you expect to see?
f.close();
delete [] tempn;
return 1;
}
when i run this prg and try to read a file of 6 lines, it prints 'i am
in' 6 times but the file descrp. is printed out as 0.
So? What do you expect?
While if I print
the value of the file descrp within the loop, it is ok.Why is that
happening?


Most likely the 'f' is converted to 'void*' and you see the result of
the converion (null pointer) printed. The reason for the null pointer
is simple: the stream is not in 'good' condition, it's in EOF state.

Once again: it's not a "file descriptor". There is no "file descriptor"
in standard C++. There are "file pointers" (FILE*) from the C library
and there are "file streams".

Victor
Jul 22 '05 #2
Siddharth Taneja wrote:
[snip]
when i run this prg and try to read a file of 6 lines, it prints 'i am
in' 6 times but the file descrp. is printed out as 0. While if I print
the value of the file descrp within the loop, it is ok.Why is that
happening?


What you see is *not* the file descriptor, whatever that may be.
What you see is the return value, when you use a stream object
in a boolean context (*). And that is: the streams overall state.
That is: non-zero if the stream is ready to be used, 0 if the stream
has gone into a fail state.

(*) this isn't entirely correct either, since streams dont' have a
conversion operator to bool. But they do have a conversion operator
to void* which serves the same purpose.
BTW: Your usage of eof() is wrong. In C++ eof() becomes true only
after you try *and* failed to read past the end of file. So the
typical usage pattern is this:

while( data_can_be_rea d ) {
process_data
}

// loop has terminated, figure out why

if( !eof() )
error file read terminated before eof was reached
--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #3
"Siddharth Taneja" <si************ **@gmail.com> wrote in message
news:52******** *************** ***@posting.goo gle.com...
Hi,

I have a very simple prg over here, trying to read the lines of a file

#include <iostream>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main() {

char tempn[100];

char line[40];
fstream f;
sprintf(tempn," %s/%s\0","/root/somedir/prj1/","temp.cfg ");
Note that the '\0' in your format string is not necessary,
'sprintf()' will terminate the string for you.


f.open(tempn,io s::in); // open file for reading
if(!f) {
cout<<"Could not find network.cfg in the directory"; // couldnt open
it
}
while(f.getline (line,10)) {

cout<<" i am in"<<endl;
if(f.eof())
break;
}
}
/* */ cout<<"f "<<f<<endl; //what is the file descpr
C++ does not define anything called a 'file descriptor'.
All i/o is done with 'streams of characters'. 'f' is
a stream object. It doesn't have a 'value' in the normal
sense of the word. So trying to output this 'value' doesn't
really mean anything. What 'value' were you expecting?

There is a stream member function ('operator void*()') which
will automatically convert to type 'bool', when the stream's
name is used in a boolean context (used to check the stream
state). I'm not sure if it's really valid for an implementation
to do this conversion in the context of inserting a stream
into a stream (which is essentially what you're trying to do),
but VC++ does give an error for that:

error C2679: binary '<<' : no operator defined which takes a
right-hand operand of type 'class std::basic_fstr eam<char,struct
std::char_trait s<char> >' (or there is no acceptable conversion)

It appears your compiler is simply outputting the stream state
as converted to 'bool' , either zero or one. Since your 'while'
loop will only terminate when the stream state evaluates to false,
this is why you're seeing zero for the output.
f.close();
This won't work since the stream is in 'fail' state at this
point. Call 'f.clear()' first.


delete [] tempn;
This is a very serious error. You did not allocate 'tempn'
with 'new[]'. Calling 'delete[]' on it gives undefined behavior.
The array 'tempn' is an 'automatic' object. It's memory is
automatically allocated when its scope is entered, and automatically
deallocated when the scope is exited.
return 1;
This is a nonstandard value to return from 'main()'. The only
defined values for this are zero, 'EXIT_SUCCESS', and 'EXIT_FAILURE',
(those last two are macros declared by <cstdlib> (or <stdlib.h>).
}
when i run this prg and try to read a file of 6 lines, it prints 'i am
in' 6 times
That's because for six iterations of your loop, the stream is in
'good' state, as indicated by the return value of 'f.getline()'.
but the file descrp.

C++ does not define anything called 'file descriptor'.
is printed out as 0. While if I print
the value of the file descrp within the loop, it is ok.Why is that
happening?
See above. You're simply seeing the stream state as converted to type
'bool'. Again, I'm not sure if your statement:
/* */ cout<<"f "<<f<<endl; //what is the file descpr


is even legal.

-Mike
Jul 22 '05 #4

"Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message
news:41******** *******@gascad. at...
Siddharth Taneja wrote:

BTW: Your usage of eof() is wrong.


I missed that. And you missed the misuse of 'delete[]'.

Put our two heads together, and maybe we can make a working
program. :-)

-Mike

Jul 22 '05 #5
On 5 Oct 2004 08:29:22 -0700, si************* *@gmail.com (Siddharth
Taneja) wrote in comp.lang.c++:

In addition to what others have pointed out, there is a very serious
mistake in your program:

[snip]
int main() {

char tempn[100];
[snip]
delete [] tempn;


'tempn' is an automatic array, not allocated with new []. Calling
delete [] on it causes undefined behavior.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 22 '05 #6

"Jack Klein" <ja*******@spam cop.net> wrote in message
news:ci******** *************** *********@4ax.c om...
On 5 Oct 2004 08:29:22 -0700, si************* *@gmail.com (Siddharth
Taneja) wrote in comp.lang.c++:

In addition to what others have pointed out, there is a very serious
mistake in your program:

[snip]
int main() {

char tempn[100];


[snip]
delete [] tempn;


'tempn' is an automatic array, not allocated with new []. Calling
delete [] on it causes undefined behavior.


I pointed this out in my reply. I guess you missed it.

-Mike
Jul 22 '05 #7

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

Similar topics

5
10141
by: simon place | last post by:
is the code below meant to produce rubbish?, i had expected an exception. f=file('readme.txt','w') f.write(' ') f.read() ( PythonWin 2.3 (#46, Jul 29 2003, 18:54:32) on win32. ) I got this while experimenting, trying to figure out the file objects modes,
6
6283
by: pembed2003 | last post by:
Hi all, Given something like: std::ofstream out_file("path"); how do I extract the file descriptor from out_file? Is it possible? What I want is to extract the file descriptor and then pass it to flock like: flock(???, LOCK_EX);
4
5993
by: lynology | last post by:
I need help trying to figure why this piece of code gives me a "Bad File descriptor error" everytime I try to run it and invoke fflush. This piece of code simple outputs a char string to the output stream. What ends up happening instead is that when outputting the first character string to the channel CG_cdukeypad_CHA.Scrpad, its gives the bad file descriptor error, causing the char string not to output. When a second char string is...
2
5047
by: John Regan | last post by:
Hello All I am trying to find the owner of a file or folder on our network (Windows 2000 Server) using VB.Net and/or API. so I can search for Folders that don't follow our company's specified folder structure and naming conventions and then send a Net send message to those users telling them to rectify. The information I want to get is when you select the file/folder and then: Properties -> Security Tab -> Advanced Button -> Owner Tab ->...
32
5867
by: Olivier | last post by:
Dear all, I thought the code ----------------------------- pt_fichier_probleme = fopen(nom_fichier, "w"); if(pt_fichier_probleme == NULL){ message_warning_s ("Erreur l'ouverture du fichier\n%s\n", (gchar *)nom_fichier); return;}
3
5272
by: Yang | last post by:
Hi, I'm experiencing a problem when trying to close the file descriptor for a socket, creating another socket, and then closing the file descriptor for that second socket. I can't tell if my issue is about Python or POSIX. In the following, the first time through, everything works. On the second connection, though, the same file descriptor as the first connection may be re-used, but for some reason, trying to do os.read/close on that...
0
6030
ashitpro
by: ashitpro | last post by:
As per the last discussion(chapter 1), here we'll try to read the group descriptor. First of all we'll try to understand what is group descriptor. AS we know, superblock and group descriptor table are duplicated in each block group. Group descriptor table is an array of group desciptors Each block group has it's own group descriptor. And it is stored in group discriptor table in sequential manner. In other word each block group has all...
3
6249
by: sejal17 | last post by:
hello Can any one tell me how to read multiple worksheets from a single excel file.I have stored that excel in xml file.so i want to read that xml that has multiple worksheet.And i want to store that multiple worksheet data in different table.How can i do it.Below is my xml file. <?xml version="1.0"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" ...
3
5402
by: sejal17 | last post by:
hello Can any one tell me how to read multiple worksheets from a single excel file.I have stored that excel in xml file.so i want to read that xml that has multiple worksheet.And i want to store that multiple worksheet data in different table.How can i do it.Below is my xml file. <?xml version="1.0"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office"...
0
9439
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10237
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10071
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10017
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
9882
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...
0
8905
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7431
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
6690
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
5326
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...

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.