c0d3rz
c0d3rz

Reputation: 679

fstream writing to a file

I needed some help writing to a file using fstream. I can currently write using the fwrite method. But I wanted to cast the data type using fwrite and write using it

Below is what I am going so far:

noOfRows = 700;
noOfCols = 100
array[0] = unsigned char [noOfRows * noOfCols]

fstream fstreamFile;
fstreamFile.open ("fstreamFile.txt", fstream::out);

for(int i = 0; i < noOfRows; i++ )
{
fwrite(array[0]+(i*noOfRows), sizeOf(unsigned char), noOfCols, fwriteFile); // writes ok
fstreamFile.write((char*) array[0]+(i*noOfCols), sizeof(unsigned char)); // doesn't write
}

Can someone please tell me what I am doing incorrectly? I get no compile error, the file just is not being written into (I have created it from before hand).

Upvotes: 0

Views: 5395

Answers (3)

David Stone
David Stone

Reputation: 28753

(char*) array[0]+(i*noOfCols)

This is taking the value of the array at position 0, then casting that value to a char * (giving some random gibberish pointer), then adding i * noOfCols to that. I believe this may be what you want:

(char*) (&array[0]+(i*noOfCols))

However, stylistically, I would recommend using C++ casts instead.

reinterpret_cast<char *>(& array[0] + i * noOfCols)

I would also recommend instead of sizeof(unsigned char) using sizeof(array[0]), just to be a bit more generic.

Also, it seems like you are trying to simulate a 2-dimensional array with a 1-dimensional array. It would be much more straightforward to declare the array as unsigned char array [noOfRows][noOfCols]; and then operate on the two dimensions normally. Your method is not getting you any performance.

Upvotes: 1

wreckgar23
wreckgar23

Reputation: 1045

You would tend to use iostreams to avoid casting.

Given an array of unsigned chars, you could instead just use an algorithm and an iterator to write the file.

#include <fstream>
#include <algorithm>
#include <iterator>

// your main and array declaration here

ofstream fstreamFile("fstreamFile.txt");
copy(
    array,
    array + sizeof(array),
    ostream_iterator<unsigned char>(fstreamFile)
);

Upvotes: 1

Rocky Pulley
Rocky Pulley

Reputation: 23301

2 things, are you looking in the correct place for the file? It should be wherever the working directory is. You should not need to create the file before hand, it will be created. Second, make sure it is creating the file, you can do this with:

if (!fstreamFile) { cout << "errorr.." << endl; }

Upvotes: 2

Related Questions