Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to read a file with an unknown character set?

Status
Not open for further replies.

Fedo

Technical User
Feb 6, 2001
9
US
I have a problem with which I have already spent a lot of time and I cannot find a solution although I intuitively feel that there is a very easy solution for it. I am completely stucked.
Here is the problem:
I have a file about which I do not know anything (neither its character set) and I want to read the whole file into a memory buffer.
I have already tried fread, fgets (fgetws), getline, streams, etc. The problem is that all those functions and techniques stop reading of the file as soon as they find 00x0 which they consifer for EOF.
Does anybody have an idea what I am doing wrong?
 
The value of EOF is not 0 [ 0x0] its actually value is -1.

The fread is the right option you choosed to read the file, it will not reading the file while reading the 0x00 or any 0 [ ASCII ]. You have to check the end of the file by using the feof() functions.

Your problem may be in the area of printing the read values.
The ASCII value 0 is used to represent the NULL.

So, print the string character by character using the for loos [ without using %s ] if required.

If possible post the code here.

Maniraja S
 
O.K.
I've finally got it. The mistake I did was not in reading a file, but in writing read memory buffer to another file. For writing I used function fprintf, which writes string (char *) to a file. The problem with this function is that writing stops as soon as 0x00 appears in the string (0x00 is considered as the end of the string). Therefore, you have to use either streams or function write, where it is possible to specify how many bytes from the buffer should be written to the file.
Here, I present my the most preferable solution to the problem. In this example I use streams and library strstream.

1.> using streams
void MainForm::ReadFile(char *MyFile, ostrstream *OutDoc)
{
// Open for reading
ifstream in(MyFile, ios_base::binary);
// Copy file into the String stream
*OutDoc << in.rdbuf();
}

In my test examle I try to write the memory buffer into the file:
void MainForm::BtnClick()
{
ostrstream OutDoc;

// Open file
ofstream in(&quot;Output.zzz&quot;, ios_base::binary);
ReadFile(&quot;MyDoc&quot;, &OutDoc);
// Copy the String stream into the file
in << OutDoc.rdbuf();
}

Good luck.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top