Jump to content

Assign variable values with a file?

- - - - -

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

#1
FrozenSnake

FrozenSnake

    Learning Programmer

  • Members
  • PipPipPip
  • 44 posts
I wish to be able to assign variables different values without the need to recompile each time. So I thought I would try to make a class/function to read a file and give the matching variable a value.

BUT! I don't know how to do this, does anyone here know any article or tutorial somewhere that explains this and how it can/should/could be done?
I tried googling "c++ +files +variables" but that didn't work so well.

Maybe it's really simple and in my head I just make it to complex anyway, anyone know a article or tutorial that explains this?

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Look up Union.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
julmuri

julmuri

    Programmer

  • Members
  • PipPipPipPip
  • 139 posts
Heres sample how to read / write values to / from files with fstream.


#include <fstream>



int main( int argc, char** argv )

{

	std::ifstream ifile;

	std::ofstream ofile;

	int test = 123456;


	ofile.open( "test.txt", std::ios_base::in | std::ios_base::out | std::ios_base::binary );

	if ( !ofile.is_open() )

	{

		// ...

		return 0;

	} // if


	// shift operator will write the value as ascii '123456'

	// ofile << test;


	// write function will write the value as binary

	ofile.write( reinterpret_cast< const char*>( &test ), 4 );

	ofile.flush();

	ofile.close();


	test = 0;


	ifile.open( "test.txt", std::ios_base::in | std::ios_base::out | std::ios_base::binary );

	if ( !ifile.is_open() )

	{

		// ...

		return 0;

	} // if


	// shift operator will read the ascii value and convert it to int

	// ifile >> test;


	// write function will read the binary value directly

	ifile.read( reinterpret_cast< char* >( &test ), 4 );

	ifile.sync();

	ifile.close();


	if ( test == 123456 )

	{

		std::cout << "read from a file"

				  << std::endl;

	} // if


 	return 0;

}



Ofcourse if you are going to save alot values you need a way to figure out where to read.