Hi my problem is as follows. I want to stream a certain amount of bytes from usbimage2.txt until my buffer is full then write them to new.txt.
My first problem is my buffer. If i give the buffer a value of say '4' it compiles with no errors. However i want to give it the size of the int 'Size_of_the_file' which i declared earlier in my file but it was just a straight forward int. When i do this i get the error

Constant expression required in function main.

Secondly when i do assign the buffer a test value of say '4' it just does nothing.
Can anyone see what im doing wrong?

thanks

char buffer[Size_of_the_file];

ifstream myFile ("C:\\bollock\\usbimage2.txt", ios::in | ios::binary);
myFile.seekg (start_byte,std::ios::beg) ;
    myFile.read (buffer, 100);

  fstream myFile2 ("new.txt", ios::out | ios::binary);
    myFile2.write (buffer, 100);

An array is a static structure, so the compiler must be able to know its size when compiling the code. The size of the file may change, depending on the file, so the compiler says "well, exactly how much space am I to reserve, then?".

You say that Size_of_the_file is a global, constant int declared earlier in the file? Your compiler doesn't think so. It is probably right.

You are also going to have problems if Size_of_the_file is less than 100, since you are reading and writing 100 bytes every time. (That is probably causing your program to crash!)

Better choices are to move the array to the heap (allocate it using new) or to use a container class (like std::string) to store it, and reading and writing only as many bytes as you have allocated.

Hope this helps.

Hi thanks for your help there, i have adapted my code now to as follows. Everything works but it only streams the first 4 characters into the output file. However Size_of_the_file is intialized to 1000 so i would expect there to be 1000 characters in he output file. Can anyone explain what is happening here?

thanks

char *buffer = new char[Size_of_the_file];
ifstream myFile ("C:\\bollock\\usbimage2.txt", ios::in | ios::binary);
myFile.seekg (start_byte,std::ios::beg) ;

	

    myFile.read(buffer,sizeof(buffer));


 ofstream g("C:\\bollock\\new.txt", ios::out | ios::binary);
    g.write(buffer, sizeof(buffer));
   g.close();

buffer is type (char *), so
sizeof( buffer ) == sizeof( char * ) == 4

Make sense?

Also, again, you are assuming something about the size of the file. What if it is different than Size_of_the_file? What if the file is super-huge?

Hope this helps.

This article has been dead for over six months. Start a new discussion instead.