Jump to content

C++ - Problem with File I/O

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
T-Wave

T-Wave

    Newbie

  • Members
  • Pip
  • 7 posts
Hi all.

Please take a look at this code:

int main(int argc, char *argv[])

{

//reads an ASCII file containing a list of numbers and writes a binary file containing the same list.


    string buffer;

    ifstream input_file, bin_input_file;

    ofstream output_file, bin_output_file;

    input_file.open("Textdoc.txt");

    output_file.open("copied.bin", ios::out | ios::binary);

    

    getline(input_file, buffer, '\0');                 //ASCII file read into buffer

    


    

    char buffer_array[buffer.length()], buffer_array_2[buffer.length()];     //Create an array big enough to store content of buffer

    

    cout << buffer_array << endl << endl;


system("PAUSE");

    return EXIT_SUCCESS;

}

The content of Textdoc.txt is: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 24 27 30 33 36 39 40 41 42 43 44 45 46 47 48 49 50 60

The last line, cout << buffer_array << endl << endl; prints the following to the screen: 20 21 24 27 30 33 36 39 40 41 42 43 44 45 46 47 48 49 50 60 P3"

Questions:
1 - How come part of the content of buffer is automatically copied into buffer_array without an explicit command for the program to do so?

2 - Assuming for some reason, that it is supposed to copy the content of buffer automatically into buffer_array, why does it start at 20? Why doesn't it copy the entire content of buffer?

I'd be extremely grateful for any help whatsoever in understanding this seemingly strange behaviour ;D. Thanks.

#2
solartic

solartic

    Learning Programmer

  • Members
  • PipPipPip
  • 95 posts
never mind

Edited by solartic, 18 September 2008 - 03:05 PM.


#3
LukeyJ

LukeyJ

    Learning Programmer

  • Members
  • PipPipPip
  • 93 posts
I'm going to guess because I've seen behaviour like this before although I'm not great at C++. Does the function used have a limit? If it is has a default limit that is too small, it could overwrite what was in it, if there is a way to manually state the size of the buffer that may work.

Well, that was me clutching at straws, I'm sure someone who knows better could help. :)

#4
morefood2001

morefood2001

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,720 posts
If you notice, he said never mind, which cues us to he solved his own problem :)

However, what exactly solved your problem for people with similar problems?

#5
solartic

solartic

    Learning Programmer

  • Members
  • PipPipPip
  • 95 posts
well actually i said never mind not the author, because the answer i gave seemed to be wrong after trying my solution on the code given above, one think i notice the problem only happen when i compiled it on windows(also tested on linux)