#### Archived

This topic is now archived and is closed to further replies.

# Storing string to a file

This topic is 5502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How can i store strings to a file? u see if i have: string name="McCall"; and i store it to file using ofstream, its just numbers in the file so obviously its kinda difficult to load from the file. Soo does the string type have any operator perhaps to get chars, not the memory address or what ever it gaved to me?

##### Share on other sites
Include your write/read code. Here that is.

I have spoken.

[edited by - Zorak on December 23, 2002 10:43:15 AM]

##### Share on other sites
name.c_str() = char version of the string?

.lick

##### Share on other sites
Here is code that shows both how to read and write strings to a file:
#include <stdio.h>int main(){    FILE* fptr;    char mystr[] = "Hello World";    char anotherstr[101];    /* Write "Hello World" to file "hi.txt" */    fptr = fopen("hi.txt", "wt"); /* w means write, t means text file */    fprintf(fptr, "%s", mystr); /* Write string mystr */    fclose(fptr);    /* Now read that string back in */    fptr = fopen("hi.txt", "rt"); /* r means read */    fscanf(fptr, "%100s", anotherstr); /* Read string in */    fclose(fptr);    /* To prove this worked, we''ll print anotherstr to the screen */    printf("The string is: %s\n", anotherstr);    return 0;}

- Andy Oxfeld

##### Share on other sites
Unfortunately that uses C style strings, and the OP was using std::string (well ''string'', which is a class anyway)

##### Share on other sites
quote:
Original post by Evil Bill
Unfortunately that uses C style strings, and the OP was using std::string (well ''string'', which is a class anyway)

Then it''s about time for the OP to learn to use C style strings

- Andy Oxfeld

##### Share on other sites
True, but still, i thought there was a way to read & write std::strings to a file.

I dunno, i don''t tend to use the STL much.

##### Share on other sites
You could write a string similarly to my example above but using stringvariablename.c_str() where I used mystr, like this:
fprintf(fptr, "%s", stringvariablename.c_str());

To read in a string, you could read it into a character array like I did, and then do:
stringvariablename = anotherstr;

- Andy Oxfeld

##### Share on other sites
Uh, what''s wrong with ofstream/ifstream?

This should work (not tested)

  #include <fstream>#include <iostream>#include <string>int main() {  std::string st = "boo";  {    std::ofstream out("test.txt");    out << st;  }  std::string st2;  {    std::ifstream in("test.txt");    in >> st2;  }  std::cout << st2 << std::endl;}

##### Share on other sites
this post was an evil twin of the one above

[edited by - civguy on December 23, 2002 12:31:20 PM]

##### Share on other sites
quote:
Original post by civguy
Uh, what''s wrong with ofstream/ifstream?

Slow, bloated, ugly, pointless, less portable. fopen style functions work nicely.

- Andy Oxfeld

##### Share on other sites
quote:
Original post by Craazer

Soo does the string type have any operator perhaps to get chars, not the memory address or what ever it gaved to me?

the array subscript operator

e.g.

  std::string foo = "bar";foo[0] = ''t''; cout << foo[2];

##### Share on other sites
okay the original poster''s question has been answered using c++, std::string and std::ostream. all they had was a misunderstanding thinking it wasn''t working wheras they were doing it exactly right.

can andy oxfeld start a new thread called ''why am i being dragged kicking and screaming from c to c++?''

##### Share on other sites
quote:
Original post by AndyOxfeld
Slow, bloated, ugly, pointless, less portable. fopen style functions work nicely.
Slow? I doubt it. Bloated? I'd say featureful, with basic features easier to use than in the f* stuff. Ugly? Compare:

    FILE* fptr = fopen("hi.txt", "rt");fscanf(fptr, "%100s", anotherstr);fclose(fptr);

Versus

  std::ifstream in("hi.txt");in >> anotherstr;

Are you blind perhaps?

Pointless? Come up with better arguments. Less portable? If your target platform doesn't have C++ compiler, then use C, ASM, whatever turns you on. But still, that sounds more like a hoax from the 80's than a valid point. Maybe 0.01% of us is targetting for platform for which there is C compiler but no C++ compiler.

[edited by - civguy on December 23, 2002 3:16:36 PM]

##### Share on other sites
quote:
Original post by civguy
much useless text..

don''t even try to talk with AndyOxfeld about file in/out. he will never accept. he''s now what everyone would call a "freak". he resists on his believe, and sees beauty in the clumpsy way to use the stuff. even while complicated, and unsave to use, he will never agree that the new stuff could be bether in some ways.

as next, he will explain you that he can''t understand why they abuse bitshifting for streaming in and out of a file..

it''s boring and ridiculous.. have fun if you want..

"take a look around" - limp bizkit

##### Share on other sites
quote:
Original post by davepermen
don't even try to talk with AndyOxfeld about file in/out. he will never accept. he's now what everyone would call a "freak". he resists on his believe, and sees beauty in the clumpsy way to use the stuff. even while complicated, and unsave to use, he will never agree that the new stuff could be bether in some ways.

as next, he will explain you that he can't understand why they abuse bitshifting for streaming in and out of a file..

it's boring and ridiculous.. have fun if you want..

"take a look around" - limp bizkit

I think the fact that you like that horrible Limp Bizkit song says enough about your tastes

If iostream has so many more features than fopen, please show me something that can be done with iostream that cannot be done with fopen syntax.

I really hope the people on these message boards do not represent the future of game developers. Back when game development used to be an art, not a commercial venture, programmers would look to write the most efficient code possible. But now apparently it is acceptable to use bloated libraries like iostream just because they are "easier".

To be honest, if you can't program well enough to write code that does not cause memory leaks or buffer overflows without resorting to using iostream, string, and STL classes, then you shouldn't be programming games.

And for those that say iostream isn't bloated... let's just look at the size of the header files:

stdio.h: 11.7kb

iostream.h, ios.h, streamb.h, istream.h, ostream.h, fstream.h: 33.2kb combined

'Nuff said?

- Andy Oxfeld

[edited by - AndyOxfeld on December 23, 2002 4:32:19 PM]

##### Share on other sites
quote:

I really hope the people on these message boards do not represent the future of game developers. Back when game development used to be an art, not a commercial venture, programmers would look to write the most efficient code possible. But now apparently it is acceptable to use bloated libraries like iostream just because they are "easier".

As computers become more powerful, its less important to use ''fast'' code, and more importnat to use code that is portable and reusable.

quote:

To be honest, if you can''t program well enough to write code that does not cause memory leaks or buffer overflows without resorting to using iostream, string, and STL classes, then you shouldn''t be programming games.

No one said that he can''t, it just makes more sense to make full use of the C++ language. File IO is slow enough anyway, so adding another couple of miliseconds to file IO functions won''t really make much difference.

quote:

And for those that say iostream isn''t bloated... let''s just look at the size of the header files:
stdio.h: 11.7kb
iostream.h, ios.h, streamb.h, istream.h, ostream.h, fstream.h: 33.2kb combined

That doesn''t really mean anything. All that shows is the size of the uncompiled source that is in the ionstream headers. Even after compiliation, you may have a larger file if you used the iostream family of functions than had you used the C style stdio functions. I wouldn''t be at all surprised if the iostream functions used C style stdio functions at their lowest level (although i haven''t actually checked). The iostream functions may not be the fastest, but they certainly make it easy to reuse code. If you include a library that defines a pile of functions, but only uses one or two, a deacent compiler should be able to exclude the unused functions to reduce code bloat.

Civguy, Daveperman & Petewood, I agre with all you points, but still, theres no need to provoke a flame war...

##### Share on other sites
quote:
I really hope the people on these message boards do not represent the future of game developers. Back when game development used to be an art, not a commercial venture, programmers would look to write the most efficient code possible. But now apparently it is acceptable to use bloated libraries like iostream just because they are "easier".

Have you even used a profiler? Even the barebones one in VC6 will show you that A COMPLETELY MINISCULE PROPORTION of time is spent on the iostreams. Have you even read through Stroustrup much? The chief goals of C++ are to be small, efficient, and support a much stronger form of type checking that is enforced at compile time. The iostreams fit this description perfectly. A newbie using printf will pass the wrong type to the va_args portion and possibly crash the program. This is nearly impossible to do with iostreams. When it comes to learning the language, iostreams make a heck of a lot more sense than the random function calls that C espouses.

In short: get over yourself. Preferring C over C++ does not make you superior in any way. If you haggle over EXE sizes as much as you claim to then you should be programming everything in raw assembler anyway, and use self-expanding EXEs so you can eek every last opcode out of your executables. Me...I''ll be doing something useful.

##### Share on other sites
quote:
Original post by AndyOxfeld
If iostream has so many more features than fopen, please show me something that can be done with iostream that cannot be done with fopen syntax.

iostream is a class, an object with plenty of functionality.

fopen is a function with one functionality, namely opening a file. If you are going to have a go for your cause, atleast write what you mean to say. As it is now, that was the dumbest statement ive heard today.

quote:

stdio.h: 11.7kb
iostream.h, ios.h, streamb.h, istream.h, ostream.h, fstream.h: 33.2kb combined

It could be alot more comments? Preprocessor commands? That was most likely the second dumbest statement ive heard today.

---8<---[snip]

And the original poster wanted a C++ answer not a C answer which he got by now and therefor there is no point in ventilating anymore over this at all.

I have spoken.

##### Share on other sites
quote:

Then it''s about time for the OP to learn to use C style strings

I disagree.

##### Share on other sites
quote:
Original post by Craazer
How can i store strings to a file?

u see if i have:
string name="McCall";

and i store it to file using ofstream, its just numbers in the file so obviously its kinda difficult to load from the file.

Soo does the string type have any operator perhaps to get chars, not the memory address or what ever it gaved to me?

Just be more careful when your string consist of empty spaces. Reading is slightly different when there's empty spaces in between your string. IMO, writting-out and reading-in line-by-line is the easiest. See also getline() or fgets().

[EDIT] Oh, your solution has been mentioned above (in C and C++ both version), so I needn't repeat it here.

[edited by - DerekSaw on December 23, 2002 10:33:57 PM]

##### Share on other sites
quote:
Original post by AndyOxfeld
Here is code that shows both how to read and write strings to a file:
#include <stdio.h>int main(){    FILE* fptr;    char mystr[] = "Hello World";    char anotherstr[101];    /* Write "Hello World" to file "hi.txt" */    fptr = fopen("hi.txt", "wt"); /* w means write, t means text file */    fprintf(fptr, "%s", mystr); /* Write string mystr */    fclose(fptr);    /* Now read that string back in */    fptr = fopen("hi.txt", "rt"); /* r means read */    fscanf(fptr, "%100s", anotherstr); /* Read string in */    fclose(fptr);    /* To prove this worked, we'll print anotherstr to the screen */    printf("The string is: %s\n", anotherstr);    return 0;}

- Andy Oxfeld

It won't work. You need fgets() and fputs() pair. The output is "Hello" only.

And the cin/cout solution too need special tricks to read string with whitespaces.

[edited by - DerekSaw on December 23, 2002 10:53:59 PM]