473,748 Members | 4,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Failed to read a file

Hi All,

Here is the problem

char* memblock;

std::ifstream file(sFileName, ios::in|ios::bi nary);
if (file.is_open() )
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the complete file content is in memory";

delete[] memblock;
}

I tried to read a say "JPEG/GIF/EXE/etc.. " files.

I checked in to debugger and find that It reads only
BM╤ from file it means that it does not read till the end of file can
you please let me know why this problem I am facing

One more thing My project is a Unicode one I hope this one will not
affect the File I/O functions

Thanks
Anup

Nov 2 '07 #1
9 3464
On Nov 2, 4:43 pm, Matrixinline <anup.kata...@g mail.comwrote:
Hi All,

Here is the problem

char* memblock;

std::ifstream file(sFileName, ios::in|ios::bi nary);
if (file.is_open() )
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the complete file content is in memory";

delete[] memblock;

}

I tried to read a say "JPEG/GIF/EXE/etc.. " files.

I checked in to debugger and find that It reads only
BM¨h from file it means that it does not read till the end of file can
you please let me know why this problem I am facing

One more thing My project is a Unicode one I hope this one will not
affect the File I/O functions

Thanks
Anup
I guess you do not allocat enough momery for memblock .Just guess.

Nov 2 '07 #2

"Matrixinli ne" <an**********@g mail.comwrote in message
news:11******** **************@ i38g2000prf.goo glegroups.com.. .
Hi All,

Here is the problem

char* memblock;

std::ifstream file(sFileName, ios::in|ios::bi nary);
if (file.is_open() )
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the complete file content is in memory";

delete[] memblock;
}

I tried to read a say "JPEG/GIF/EXE/etc.. " files.

I checked in to debugger and find that It reads only
BM? from file it means that it does not read till the end of file can
you please let me know why this problem I am facing

One more thing My project is a Unicode one I hope this one will not
affect the File I/O functions

Thanks
Anup

===========

You open the file, get the position. The position at this point is 0. Did
you mean to add the line
file.seekg (0, std::ios::end);
before the size = file.tellg();?

It is hard to say, because this code doesn't compile as written for me.

This, compilable version, runs for me and shows the output of a txt file (I
don't care to look at binary data at this time).

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

int main()
{
char* memblock;

std::string sFileName="cons ole5.cpp";
std::ifstream file(sFileName. c_str(), std::ios::in|st d::ios::binary) ;
if (file.is_open() )
{
file.seekg (0, std::ios::end);
unsigned int size = file.tellg();
std::cout << "Size:" << size << "\n";
memblock = new char [size];
file.seekg (0, std::ios::beg);
file.read (memblock, size);
file.close();
std::cout << "the complete file content is in memory\n";
for ( int i = 0; i < size; ++i )
std::cout << memblock[i];

delete[] memblock;
}

}
Nov 2 '07 #3
On Nov 2, 10:05 am, "Jim Langston" <tazmas...@rock etmail.comwrote :
"Matrixinli ne" <anup.kata...@g mail.comwrote in message
[...]
You open the file, get the position. The position at this
point is 0. Did you mean to add the line
file.seekg (0, std::ios::end);
before the size = file.tellg();?
This may work on a lot of systems, but formally, there's no
guarantee that the results of tellg() can be implicitly
converted to an integral type, and there's even less of a
guarantee that they represent the number of bytes in the file
between the current position and the beginning of the file; a
system can use any sort of magic encoding it wants. (In
practice, of course, it probably works under Unix, and for files
opened in binary under Windows. Provided the files aren't too
big.)

The simplest and surest way of reading all of a file into memory
is:

std::vector< char v(
(std::istreambu f_iterator< char >( file )),
(std::istreambu f_iterator< char >()) ) ;

If you're unsure of the file size, you might want to wrap it in
a try block, catching bad_alloc.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Nov 2 '07 #4
On Fri, 02 Nov 2007 05:39:15 -0700, James Kanze
<ja*********@gm ail.comwrote:
>The simplest and surest way of reading all of a file into memory
is:

std::vector< char v(
(std::istreambu f_iterator< char >( file )),
(std::istreambu f_iterator< char >()) ) ;

If you're unsure of the file size, you might want to wrap it in
a try block, catching bad_alloc.
James, could you elaborate on this mechanism for me? I've been using
the

file.seekg(0,io s::end);
file.tellg();

method for ages. How does your contruction work, and will a simple
v.size() give me the data size afterwards?
--
PGP key ID 0xEB7180EC
Nov 2 '07 #5
On Nov 2, 2:05 pm, Keith Willis <m...@privacy.n etwrote:
On Fri, 02 Nov 2007 05:39:15 -0700, James Kanze
<james.ka...@gm ail.comwrote:
The simplest and surest way of reading all of a file into memory
is:
std::vector< char v(
(std::istreambu f_iterator< char >( file )),
(std::istreambu f_iterator< char >()) ) ;
If you're unsure of the file size, you might want to wrap it in
a try block, catching bad_alloc.
James, could you elaborate on this mechanism for me?
It's just a more or less classical use of streambuf_itera tor;
you can construct a vector with an iterator pair of any type.
All it does is read the entire file into the vector, in the
constructor.
I've been using the
file.seekg(0,io s::end);
file.tellg();
method for ages.
It seems to be a common idiom, however: file.tellg() returns a
streampos, which must be a class type (it is required to contain
multi-byte state, as well as the physical position in the file).
The standard requires an implicit conversion of this to
streamoff, but because streampos is a user defined type, this
must be a user defined conversion. The standard also requires
that streamoff be convertible into an integral type. However:
if streamoff is also a class type, the conversion of a streampos
to an integral type involves two user defined conversions, and
can't occur implicitly. Typically, streamoff is a typedef to
an integral type, so you're OK. But there are still two
potential problems: the mapping of the integral value of
streamoff may not be linear (not likely on a system modeling
files as byte streams, like Unix or Windows, but on more complex
systems, who knows), and the actual file size might not fit in
the target integral type. (On all of the systems I use, int is
32 bits, but files can be---and often are-- considerably bigger
than what will fit into 32 bits.)
How does your contruction work, and will a simple v.size()
give me the data size afterwards?
It works because it constructs a vector with the contents of the
file, by reading it. And v.size() will give you the exact value
of the number of bytes read.

--
James Kanze (GABI Software) mailto:ja****** ***@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34

Nov 2 '07 #6
On Fri, 02 Nov 2007 06:44:41 -0700, James Kanze
<ja*********@gm ail.comwrote:
>On Nov 2, 2:05 pm, Keith Willis <m...@privacy.n etwrote:
>On Fri, 02 Nov 2007 05:39:15 -0700, James Kanze
><james.ka...@g mail.comwrote:
>The simplest and surest way of reading all of a file into memory
is:
std::vector< char v(
(std::istreambu f_iterator< char >( file )),
(std::istreambu f_iterator< char >()) ) ;
>If you're unsure of the file size, you might want to wrap it in
a try block, catching bad_alloc.
>James, could you elaborate on this mechanism for me?

It's just a more or less classical use of streambuf_itera tor;
you can construct a vector with an iterator pair of any type.
All it does is read the entire file into the vector, in the
constructor.
OK, I'm trying this and am having some problems; what am I doing
wrong?! Given this simple example:

//-------------------------------------------
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int main(int argc, char** argv)
{
if (argc 1)
{
ifstream file(argv[1], ios::binary);
vector<unsigned charv(istreambu f_iterator<unsi gned char>(file),
istreambuf_iter ator<unsigned char>());

cout << "Read " << v.size() << " bytes from '"
<< argv[1] << "'\n";
}
return(0);
}
//-------------------------------------------

I get the following at compile time:

xx.cc: In function `int main(int, char**)':
xx.cc:16: error: request for member `size' in `v', which is of
non-class type `std::vector<un signed char, std::allocator< unsigned
char ()(std::istream buf_iterator<un signed char,
std::char_trait s<unsigned char, std::istreambuf _iterator<unsig ned
char, std::char_trait s<unsigned char (*)())'

--
PGP key ID 0xEB7180EC
Nov 5 '07 #7
On Mon, 05 Nov 2007 09:49:46 +0000, Keith Willis <me@privacy.net >
wrote:
>OK, I'm trying this and am having some problems; what am I doing
wrong?! Given this simple example:
I know, I know - following up one's own posts is frowned upon. But I
just worked out how to use this idiom, so I thought I'd save anyone
else the time of explaining it. This version works:

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int main(int argc, char** argv)
{
if (argc 1)
{
ifstream file(argv[1], ios::binary);

istreambuf_iter ator<unsigned charstart(file. rdbuf());
istreambuf_iter ator<unsigned charend;

vector<charv(st art,end);

cout << "Read " << v.size() << " bytes from '"
<< argv[1] << "'\n";
}
return(0);
}

--
PGP key ID 0xEB7180EC
Nov 5 '07 #8
On Fri, 02 Nov 2007 06:44:41 -0700, James Kanze
<ja*********@gm ail.comwrote:
>On Nov 2, 2:05 pm, Keith Willis <m...@privacy.n etwrote:
>On Fri, 02 Nov 2007 05:39:15 -0700, James Kanze
><james.ka...@g mail.comwrote:
>The simplest and surest way of reading all of a file into memory
is:
std::vector< char v(
(std::istreambu f_iterator< char >( file )),
(std::istreambu f_iterator< char >()) ) ;
>James, could you elaborate on this mechanism for me?

It's just a more or less classical use of streambuf_itera tor;
you can construct a vector with an iterator pair of any type.
All it does is read the entire file into the vector, in the
constructor.
<snip>
>Typically, streamoff is a typedef to
an integral type, so you're OK. But there are still two
potential problems: the mapping of the integral value of
streamoff may not be linear (not likely on a system modeling
files as byte streams, like Unix or Windows, but on more complex
systems, who knows), and the actual file size might not fit in
the target integral type. (On all of the systems I use, int is
32 bits, but files can be---and often are-- considerably bigger
than what will fit into 32 bits.)
OK, I've been playing with this and have a question. Your reservation
about using the seekg() and tellg() calls was partly because the size
of the file might not be representable by an integral type. But, if I
use this istreambuf_iter ator method to read the data into my vector
vec, I then check the size of the data read using vec.size(), yes? But
vector::size() seems to return a size_type value, and that is an
unsigned integer type, at least according to
http://www.cplusplus.com/reference/stl/vector/size.html, so I still
can't read files with a size larger than will fit in 32 bits...

Or am I missing something here?

--
PGP key ID 0xEB7180EC
Nov 5 '07 #9
On Nov 5, 12:52 pm, Keith Willis <m...@privacy.n etwrote:
On Fri, 02 Nov 2007 06:44:41 -0700, James Kanze
<james.ka...@gm ail.comwrote:
On Nov 2, 2:05 pm, Keith Willis <m...@privacy.n etwrote:
On Fri, 02 Nov 2007 05:39:15 -0700, James Kanze
<james.ka...@gm ail.comwrote:
The simplest and surest way of reading all of a file into memory
is:
std::vector< char v(
(std::istreambu f_iterator< char >( file )),
(std::istreambu f_iterator< char >()) ) ;
James, could you elaborate on this mechanism for me?
It's just a more or less classical use of streambuf_itera tor;
you can construct a vector with an iterator pair of any type.
All it does is read the entire file into the vector, in the
constructor.
<snip>
Typically, streamoff is a typedef to
an integral type, so you're OK. But there are still two
potential problems: the mapping of the integral value of
streamoff may not be linear (not likely on a system modeling
files as byte streams, like Unix or Windows, but on more complex
systems, who knows), and the actual file size might not fit in
the target integral type. (On all of the systems I use, int is
32 bits, but files can be---and often are-- considerably bigger
than what will fit into 32 bits.)
OK, I've been playing with this and have a question. Your
reservation about using the seekg() and tellg() calls was
partly because the size of the file might not be representable
by an integral type.
Partially. Formally, there is no requirement of convertibility,
and no requirement that the integral values resulting from the
conversion will be meaningful in any traditional sense of the
word. Practically, at least under Windows and (probably most)
Unix, however, the only real problem will be the fact that the
size of the file typically isn't representable as an int.
(If you use long long, perhaps, you won't have a problem.)
But, if I
use this istreambuf_iter ator method to read the data into my vector
vec, I then check the size of the data read using vec.size(), yes? But
vector::size() seems to return a size_type value, and that is an
unsigned integer type, at least according tohttp://www.cplusplus.c om/reference/stl/vector/size.html, so I still
can't read files with a size larger than will fit in 32 bits...
Or am I missing something here?
Not really. The main difference is that if you overflow reading
into an std::vector, you get an exception (bad_alloc); if you
overflow converting to an int, you get some implementation
defined value which has little relationship to the actual size.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Nov 5 '07 #10

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

Similar topics

3
2594
by: Patrice | last post by:
Hi, I would to call fopen function several time in my application. This application permits to read files which path is registered in a configuration file. For exemple: File 1 = toto.txt File 2 = tot2.txt ....File N = TotoN.txt Then, I read each file (one by one), get adress of the beginning of data and size of data.
4
8072
by: zhimin | last post by:
Hi, I'm writing a program to send large file(100m) through dotnet using TCPListener & TCPClient, I'm sending the file with a ask and response loop: 1. Client send a flag 1 to server indicate it has data send to server. 2. Client send the buffer block size. 3. Client send the actual buffer to the server. 4. Server send a flag 1 to client indicating that the buffer has been successfully receeived. 5. The next loop until all data of the...
0
2095
by: Jeff Reed | last post by:
I am experiencing the the problem outlined the below. Unfortunately, I am using WinXP and I not sure if I can apply the solution due to lack of security control Any feed back would be apreciated http://support.microsoft.com/default.aspx?scid=kb;EN-US;31795 FIX: "Failed to Start Monitoring Directory Changes" Error Message When You Browse to an ASP.NET Pag View products that this article applies to This article was previously...
9
3214
by: Tim D | last post by:
Hi, I originally posted this as a reply to a rather old thread in dotnet.framework.general and didn't get any response. I thought it might be more relevant here; anyone got any ideas? My questions are below... "David Good" wrote: > We have a network running both Win2k and Win2k3 webservers and our web sites > reside on a UNC network share that happens to be a Network Appliance NAS.
0
3151
by: Simon | last post by:
Hi I try to open a CR report file located on the network path from a web form developed with vs2003 and CR for Visual Studio, but the Load method of ReportDocument object always return error. --------------------- Load report failed. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information
0
3187
by: Nicolas Noakes | last post by:
Hello, I posted this 2005-01-16 in microsoft.public.sqlserver.setup, but have had no replies yet... We are running SBS 2003 Standard Edition with SP1, and WSUS (Windows Server Update Services). All was well until I tried to install the folloing update, which failed:
4
4808
by: technocrat | last post by:
I am trying to update a million rows in a table and doing this reading from a file which has the record pkids and constructing a preparedstatemtn with that pkid and adding it to the batch... count is the recordnumber read from the file... so for every count the st is added to the batch.....since for every record read from the file has a update statement(st)... st.setString(1, arg1); st.setString(2, arg2); st.setString(3, arg3);
16
2236
by: Gary Wessle | last post by:
Hi please help with this. std::fstream iofs( f.c_str(), std::ios::in|std::ios::out ); std::cout << f << '\n' << iofs.is_open() << std::endl; puts out **************************************************************** pair_status/myPair
1
12384
by: edmundleungs | last post by:
In our veritas netbackup for DB2 on AIX, the backup could be done successfully and the backup image would be listed using bplist on the AIX client. I have made several backup image, but only one image would be restored successfully. Restore with all the other images would get SQL2025N An I/O error "515" occurred on media "VENDOR". readCommFile: ERR - timed out after 900 seconds while reading from /...
2
2857
by: rasmidas | last post by:
Hi, I am getting the following error while I am running my application. EXITING AddToEventLog() EXITING WriteNoDocProdEvent() EXITING SubstituteSummitMessages() EXITING dmgDocumentCreate () File: ssybdb12_imp.cc Line: 1484 CT_Library: ct_result() failed File: ssybdb12_imp.cc Line: 1484 Incorrect syntax near '132'. t@1 (l@1) signal SEGV (no mapping at the fault address) in GenerateDocument at 0xedda2ee4
0
8984
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8823
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
9530
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
9363
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...
0
8237
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
6793
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
4593
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...
0
4864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2206
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.