Thread: Retrieving data from a file

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    31

    Retrieving data from a file

    You may have already seen my questions about how to output to a file, now that i have that sorted out, now's time to learn how to get it back!

    i tried this
    Code:
       ifstream open((cName + ".txt").c_str());
       fin >> getline(2);
    the first like seemed to work ok, but
    Code:
    fin >> getline(2);
    didnt seem to work for me. for some reason or another i cant seem to figure out how to get fin to declare where its getting info from.

    Thanx for the help in advance!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Perhaps you should read about how getline is supposed to be used, e.g., by looking it up on cppreference.com
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Here's a trick that works, I doubt it is the best way to do this tho:

    Code:
        	string name="tmp.txt";
    	ifstream file(name.c_str());
    	while (!file.eof()) cout << (char)file.get();
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Feb 2010
    Posts
    31
    Laserlight, I did look it up, thats how i knew it even existed. I'm just not sure how to use it yet. I'm new to c++ so the documentation starts to look like japanese to me, and i dont speak japanese.
    My only experience with coding is actionscript. So this is all very new to me, im sorting my way through it with the help of a lot of nice people here (you included).

    Basically, i understand the logic, just dont understand the syntax.
    If i try to code it myself, then have it not work, someone shows me the correction, then i rewrite the code a few times...thats how i learn this kinda stuff.

    Reading documentation on it just doesnt register with me...i have 2 c++ books, but unless i can see it work or not work, I dont really get it.

    Anyway, im just trying to read the file, and cout the data.

    EDIT: I looked up the link in your signature LaserLight. After seeing that documentation i see that i've used it incorrectly.
    Last edited by kamitsuna; 02-24-2010 at 11:37 AM.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by MK27
    Here's a trick that works, I doubt it is the best way to do this tho:
    The same general recommendation to avoid using feof() to control a loop applies here, except this time it is member function eof(). A suitable fix:
    Code:
    char c;
    while (file.get(c))
    {
        cout << c;
    }
    Quote Originally Posted by kamitsuna
    I looked up the link in your signature LaserLight. After seeing that documentation i see that i've used it incorrectly.
    Ah, so you figured it out?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by kamitsuna View Post
    Reading documentation on it just doesnt register with me...i have 2 c++ books, but unless i can see it work or not work, I dont really get it.
    Yeah, grokking documentation is the same as programming: the more you do it, the easier it becomes.

    Usually what docs lack are working examples. Here's something that reads a text file into a vector of strings, then prints them out:
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    using namespace std;
    
    int main() {
    	string name="tmp.txt";
    	ifstream file(name.c_str());
    	char buf[1024];
    	vector<string> data;
    	int i, len;
    
    	while (file.getline(buf,1024)) data.push_back(buf);
    
           	file.close();
                     
    	len = data.size();
    	for (i=0;i<len;i++) cout << data[i] << endl;
    
    	return 0;
    }
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by laserlight View Post
    The same general recommendation to avoid using feof() to control a loop applies here, except this time it is member function eof().
    Yeah, in fact that illustrates the principle because it outputs the EOF ("�") before it stops. Just foolin' around.

    In real life I'd probably go with your method or the one above.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  8. #8
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Quote Originally Posted by MK27 View Post
    Yeah, grokking documentation is the same as programming: the more you do it, the easier it becomes.

    Usually what docs lack are working examples. Here's something that reads a text file into a vector of strings, then prints them out:
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    using namespace std;
    
    int main() {
    	string name="tmp.txt";
    	ifstream file(name.c_str());
    	char buf[1024];
    	vector<string> data;
    	int i, len;
    
    	while (file.getline(buf,1024)) data.push_back(buf);
    
           	file.close();
                     
    	len = data.size();
    	for (i=0;i<len;i++) cout << data[i] << endl;
    
    	return 0;
    }
    I rarely will recommend a programming book b/c frankly most have about 10% useful material. However I would suggest taking a peek at this:
    Amazon.com: The C++ Standard Library: A Tutorial and Reference (0785342379266): Nicolai M. Josuttis: Books

    Because it is chock-full of both theory AND working examples showing how things work. I really like it. A senior dev gave this book to me one year for a gift and I find it be one of the most useful non-platform-specific coding books that I own...

    In the related books dept, speaking of something with lots of example code, seek out this baby:



    Edit: Nuts..in edit mode the URL is there in the proper tags but published it is not. Anyhow the name is the Oreilly C++ Cookbook.
    End edit.
    What makes this one good is if you want to skip theory (like trying to get things done on a deadline) and just quickly need a working example of how to do programming job XXX, this "cookbook" is great, just short chapters with "recipes" for doing everything from debugging to using Boost to whatever. Good stuff.
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  9. #9
    Registered User
    Join Date
    Feb 2010
    Posts
    31
    hehe, im still lost on this topic....oh well, i think im just too new to coding to get it quite yet.

    Basically i'm looking to (later on) start working on my own game. Right now, im just trying to get a very basic character creation and character save going.

    1) User inputs character creation stats
    2) Stats saved to a file under the character name
    3) Stats can then be retrieved and used in the coding of the game.

    I have a very VERY basic completion of 1 and 2. 3 is givin me trouble....or maybe someone might be able to direct me to a better way to do all of this.

    Basically all the code im writing right now is junk, its just for learning. I will then go back and re-code everything later to finalize my ideas.

  10. #10
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    IMO the best way to do this is create a "character struct" containing all the stats:
    Code:
    typedef struct {
        char name[64];
        int level;
        [...etc...]
    } char_stats;
    and then serialize it:
    SourceForge.net: Serialization - cpwiki
    Serialization means you can write this whole struct straight out and read it straight back in without doing any transformation, such as having to turn the ints into text (then back into ints again).

    Just make sure you use finite, fixed length char arrays, etc, for the data, and not dynamic types like "string".
    Last edited by MK27; 02-25-2010 at 09:11 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by kamitsuna
    I have a very VERY basic completion of 1 and 2. 3 is givin me trouble....or maybe someone might be able to direct me to a better way to do all of this.
    Well, if you can do part 2, part 3 would be a matter of "reversing" what you did for part 2. In fact, it might even just mimic what you did for part 1.

    An alternative to consider, if you are willing to get side tracked, is to use an embedded database like SQLite. SQLite's library interface is a C API though, and I do not really like any of the C++ wrappers out there other than my own (which is um, rather lacking in documentation and such at the moment).

    Quote Originally Posted by MK27
    IMO the best way to do this is create a "character struct" containing all the stats:
    (...)
    and then serialize it:
    SourceForge.net: Serialization - cpwiki
    Serialization means you can write this whole struct straight out and read it straight back in without doing any transformation, such as haveing turning the ints into text (then back into ints again).

    Just make sure you use finite, fixed length char arrays, etc, for the data, and not dynamic types like "string".
    That is certainly possible, but the limitation of POD types and the possible lack of portability even then is a bummer. A library like Boost.Serialization can help, but it is also a little of a side track having to learn how to use it, and how to compile Boost or get a pre-built version to work.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User
    Join Date
    Feb 2010
    Posts
    31
    well i thought what i was doing was reversing the process, but i guess it doesnt quite work that way.

    Really what i did was just apply some values to some variables, then i posted an fout with those variables.

    But retrieving them from the file seems to be a much harder task.

    i cant get fin to work...

    This is how i did the output. The text file basically looks like a very simple .cpp file.
    Code:
    	ofstream fout((cName + ".txt").c_str());
    	fout << "cName = " << cName << ";" << endl << "cStr = " << cStr << ";" << endl << "cIntel = " 
    << cIntel << ";" << endl << "cAgi = " << cAgi << ";" << endl << "cCon = " << cCon << ";"
     << endl << "cSpe = " << cSpe << ";" << endl << "cNin = " << cNin << ";" << endl;
    but for some reason i cant sort out how to get that data back into my application from the file...
    I cant cout any of the data from the file, i cant seem to retrieve any of it...

  13. #13
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    O_o

    How are you "getting" the data from the file? (Post your input code.)

    Describe, with words, exactly what you are doing with those statements. The more specific you are the better you'll understand what you need to do to reverse the process.

    There is nothing wrong with allowing arbitrary ordering of values, but you may be better served at this point in your education with a strictly ordered file format.*

    [edit]
    "SourceForge.net: Serialization - cpwiki"

    Wow. That is a really bad explanation of serialization.
    [/edit]

    Soma

    * Say "int" always comes first on the line, "agility" second, etc..

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by phantomotap View Post
    "SourceForge.net: Serialization - cpwiki"

    Wow. That is a really bad explanation of serialization.
    "Serialization is the process of saving any form of data directly to a file in the same form as it is being used in a running program. The file can then be read back in at a later point -- such as tomorrow or next year -- and used by the same or another program."

    "You can store anything effectively by serializing it. Bitmap images are just serialized pixel data; .wav files are serialized pcm data. A simple database could be a serialized array of structs."

    There's nothing inaccurate or misleading about it -- and you are welcome to add to it if you think it is incomplete in some way.

    I intended that as a simple practical demonstration, since there are already plenty of long-winded, exhaustive articles (even entire books) on the topic. IMO unless you are an obscurantist, serialization is a dead simple concept which should not require much explanation.

    http://en.wikipedia.org/wiki/Obscurantism

    Plenty of programmers and doc writers do fall into this category, I know.
    Last edited by MK27; 02-25-2010 at 09:04 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by MK27
    There's nothing inaccurate or misleading about it
    There are two things that are inaccurate about that definition: the result of the serialisation does not necessarily have to be saved in a file, and the serialisation format does not necessarily have to be "the same form as it is being used in a running program".
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. Bitmasking Problem
    By mike_g in forum C++ Programming
    Replies: 13
    Last Post: 11-08-2007, 12:24 AM
  4. File Database & Data Structure :: C++
    By kuphryn in forum C++ Programming
    Replies: 0
    Last Post: 02-24-2002, 11:47 AM