• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
AntonioR

Reading from a text file (c++)

12 posts in this topic

Hi, I need some help.

I want to be able to write some variable values in a text file and then read it from inside the application.

1.
Text file example :
[code]
window=0
screenwidth=800
screenheight=600
app_title=my project
[/code]

So i want to read "window" and then its value, and then apply that value to appropriate variable inside the code.
Also I want to be able to read string or char values.

2.
I would also want to put more variables in the same row, and the read it one by one:
[code]1 0 day month 1000 500[/code]
0

Share this post


Link to post
Share on other sites
So which bit are you having a problem with? Reading from a file? Splitting it at the =? Determining whether it's a string or a char?

No-one here is going to just do it for you.

But as a start look into strings, iostream, and data structures.
0

Share this post


Link to post
Share on other sites
Actually I wouldn't go that route (manually parsing using streams) for a configuration file. Find an existing configuration file library with a syntax that you like and just use that. INI files are strangely popular and so are XML files. There's also boost::program_options for a possibility.
0

Share this post


Link to post
Share on other sites
For a quick and easy bit of string manipulation if you have access to boost I'd recommend looking at boost::split (within boost/algorithm/string.hpp).
0

Share this post


Link to post
Share on other sites
I just need it for some simple stuff, I don't want to use a whole new library for that.

I know something about iostream, I can read numbers like this.

[code]
ifstream filein("config.txt");
filein >> fullscreen >> SCREENW >> SCREENH ;
[/code]

But the text file has just numbers inside so it won't be readable if I add some new stuff.
[code]
1
1024
768
[/code]

So I guess [quote]Splitting it at the =? Determining whether it's a string or a char?[/quote] is the actual problem.
0

Share this post


Link to post
Share on other sites
If you are going to do it that way (roll your own), I think the basic process is:

1) read the [i]line[/i]
2) find offset of '='
3) read before the '=' into a token variable
4) read behind the'=' into a value variable
5) switch on the token to assign the value variable to the correct program variable.
6) repeat with next line
0

Share this post


Link to post
Share on other sites
I managed to find some code example, it works:

[code]bool LoadSettings(int *Width, int *Height, int *Fullscreen)
{
FILE* fp;

char string[500];
fp = fopen("config.txt","r");

if (fp!=NULL)
{
char item[300];
char value[300];

while (fgets (string , 300 , fp)!=NULL)
{
//sscanf(string,"%s %[^\n]",&item, &value);
sscanf(string,"%s %s",&item, &value);

if (strcmp(item, "width")==0)
{
*Width = atoi(value);
}
else if (strcmp(item, "height")==0)
{
*Height = atoi(value);
}
else if (strcmp(item, "fullscreen")==0)
{
*Fullscreen = atoi(value);
}
}
}
else
{
return false;
}

}[/code]

Txt file:
[code]
width 1024
height 768
fullscreen 0
[/code]
0

Share this post


Link to post
Share on other sites
well, you could simply use
[code]
while (fgets (string , 300 , fp)!=NULL)
{
sscanf(string,"width %d",Width);
sscanf(string,"height %d",Height);
sscanf(string,"fullscreen %d",Fullscreen);
}[/code]

If the string is not matching, the variables won't be affected, so it can be simple as that. You can even check the return value of sscanf (look it up)

But that's C, not C++. I'm sure C++ has better methods
0

Share this post


Link to post
Share on other sites
Here is what I have been using for awhile, it doesn't read everything at once, but you can continually check the file for various settings.
Feel free to use it or make one yourself based on this, Its a modified version from some tutorial I read about 5 years ago, sorry but I do not have the link :/

ReadConfig.h

[code]//Read a specific variable from our config file and return its value
//This is our error logging class
#ifndef READCONFIG_OBJECT

#define READCONFIG_OBJECT

#include <winsock.h>
#include <stdio.h>
#include <io.h>
#include <FCNTL.H>
#include <iostream>
#include <fstream>
#include <string>
#include <list>
using namespace std;

#define MAX_STRING 255



int ReadConfigInt(char* Filename,char* Variable); //return -1 on fail, -2 on file not found
string ReadConfigString(const char* Filename,char* Variable); //returns NULL on failure

#endif [/code]

ReadConfig.cpp

[code]//Read config
#include "stdafx.h"
#include "ReadConfig.h"

int ReadConfigInt(char* Filename,char* Variable)
{


char line[MAX_STRING];
memset(line,0,MAX_STRING);
ifstream myconfig(Filename);
if(!myconfig)//could not open file
{
return NULL; //-2 file not found
}

while(!myconfig.eof())
{

myconfig.getline(line, MAX_STRING); // delim defaults to '\n'
if(myconfig)
{
if(line[0] == '/') //we are skipping this line
{ // skip comment line
continue;
}
else
{


char *pointerchar = NULL;
char var[MAX_STRING] = {'\0'}; // variable name
char val[MAX_STRING] = {'\0'}; // value its set to
size_t length =0;
pointerchar = strchr(line, '\n'); // find our newline
if(pointerchar != NULL)
{
*pointerchar = '\0'; //change newline to null character
}
length = strlen(line);
pointerchar = strchr(line, '='); //find our equals character
if(pointerchar == NULL)
{
return NULL; //failure
} //Parse Error

memcpy(var, line, pointerchar - line);// get the part before the first =
pointerchar++;// skip the actual '=' sign
memcpy(val, pointerchar, (line+length)-pointerchar);// get the value of the var
if (strcmp(var,Variable)==0)//see if we found it
{
return atoi(val);
}
}

}

}

myconfig.close();


return NULL; //didnt find that variable
}



string ReadConfigString(const char* Filename,char* Variable)
{


char line[MAX_STRING];
memset(line,0,MAX_STRING);
ifstream myconfig(Filename);
if(!myconfig)//could not open file
{
return "Unknown";
}

while(!myconfig.eof())
{

myconfig.getline(line, MAX_STRING); // delim defaults to '\n'
if(myconfig)
{
if(line[0] == '/') //we are skipping this line
{ // skip comment line
continue;
}
else
{


char *pointerchar = NULL;
char var[MAX_STRING] = {'\0'}; // variable name
char val[MAX_STRING] = {'\0'}; // value its set to
size_t length =0;
pointerchar = strchr(line, '\n'); // find our newline
if(pointerchar != NULL)
{
*pointerchar = '\0'; //change newline to null character
}
length = strlen(line);
pointerchar = strchr(line, '='); //find our equals character
if(pointerchar == NULL)
{
return NULL;
} //Parse Error

memcpy(var, line, pointerchar - line);// get the part before the first =
pointerchar++;// skip the actual '=' sign
memcpy(val, pointerchar, (line+length)-pointerchar);// get the value of the var
if (strcmp(var,Variable)==0)//see if we found it
{
return val;
}
}

}

}

myconfig.close();


return NULL; //didnt find that variable
}[/code]
0

Share this post


Link to post
Share on other sites
Doing the same in c++:
[code]
#include <string>
#include <fstream>

bool LoadSettings(int &Width, int &Height, int &Fullscreen)
{
std::ifstream file("config.txt");
if(!file.is_open())
{
return false;
}
std::string line;
while(std::getline(file, line))
{
std::stringstream stream(line);
std::string name;
int value;
if(stream >> name >> value)
{
if(name == "width")
{
Width = value;
}
else if(name == "height")
{
Height = value;
}
else if(name == "fullscreen")
{
Fullscreen = value;
}
else
{
std::cerr << "Unknown config name: " << name << '\n';
}
}
else
{
std::cerr << "Failed to parse line: " << line << '\n';
}
}
}
[/code]
Note this also features more robust error checking. The code you posted fails to fclose() the file you fopen(), among other issues.

I would not recommend using yewbie's code, it is terrible.
2

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1304520716' post='4806425']
Note this also features more robust error checking. The code you posted fails to close the file, among other issues.

I would not recommend using yewbie's code, it is terrible.
[/quote]

Heh, I am not going to defend what I posted as good code but the tutorial specifically said that when ifstream goes out of scope it cleanly closes the file.
And most of what is posted is directly from the tutorial. ( Edit: not that tutorials are to be trusted )

Much like the OP I only needed it for a couple of config lines and it worked fine for that.
Your code looks much better.
0

Share this post


Link to post
Share on other sites
[quote]
... when ifstream goes out of scope it cleanly closes the file.
[/quote]
That comment was directed at the OP's code, which uses fopen() but fails to call fclose(). I wrote my post before the intermediate comments, and I edited it to include a note about the code you posted, so I can see now why you might think that.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0