c++ file reading

Started by
15 comments, last by Servant of the Lord 11 years, 8 months ago
Hello.
I was using to read data from my files like this

/*text.txt*/
3
./Files/Maps/Map1.txt
./Files/Maps/Map2.txt
./Files/Maps/Map3.txt


FILE* tempFile = fopen("text.txt", "r");
if(tempFile == NULL)
{
fclose(tempFile);
}
fscanf(tempFile, "%d", &MyInt);
for(int x = 0; x < MyInt; x++)
{
char tempChar[60];
fscanf(tempFile, "%s\n", tempChar);
MyVector.push_back(tempChar);
}


But its really bugging me that i am limited to "char" cause the fscanf "%s" cant store to string.

What libraries can i use to read data from .txt files to string directly , and hopefully are simple to use
Advertisement
Well you could use the iostream library.

std::ifstream file("text.txt");
std::vector<std::string> lines;
while (file) {
std::string line;
std::getline(file, line);
lines.push_back(line);
}
Note that if you use the method SiCrane suggested (which I would if I were you), you need to include [font=courier new,courier,monospace]<fstream>[/font] for [font=courier new,courier,monospace]std::ifstream[/font], and [font=courier new,courier,monospace]<string>[/font] for [font=courier new,courier,monospace]std::string[/font] and [font=courier new,courier,monospace]std::getline()[/font].

The way you're currently doing it is the C way. SiCrane's way is the C++ way.
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]
Too slow, I was about to propose:


#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
int main(int argc, char** argv)
{
ifstream stream;
stream.open("level.txt");
int numFiles;
stream >> numFiles;
cout << numFiles;
vector<string> results;
while(stream)
{
string str;
getline(stream,str);
if(str != "") // Handle empty newlines
results.push_back(str);
}
std::for_each(results.begin(),results.end(), [](string value) { cout << value << endl; });
return 0;
}



Wow, the C++ formatter is seriously broken...
I wouldn't use iostream. Something like this works for me. Imagine an input file like:

# a comment
a 3.5 3.5 yay_some_text
a 3.2 4.5 yay_some_more_text

[source lang="java"]FILE *pFile = fopen(filePath, "r"); // the file to load

char buffer[512]; // character buffer
char temp;
// read each line into the buffer
while (fgets(buffer, sizeof(buffer), pFile))
{
// switch based on leading type
switch (buffer[0])
{
case '#': // do nothing, it's a comment biggrin.png
break;
case 'a':
// set ambient color ?
sscanf(buffer, "%c %f %f %s", &temp, &someFloat, &someOtherFloat, &aString);
break;
}


}[/source]

I wouldn't use iostream.

Can you expand on that?

Stephen M. Webb
Professional Free Software Developer

Just personal preference I guess. It's a bit verbose for my liking and enforces type safety at compile time. This nags at me a bit too: http://stackoverflow...answer-5165293

Seeing how I'm really used to the fgets way, this is all, of course, highly subjective. Still, it's a valid alternative.
Type safety is a good thing. Actually it is a great thing.

And while it's true that the iostream classes can be a bit on the slow side on a lot of implementations, I would not replace them with something handrolled like that. If performance of text file parsing is an issue (in a lot of cases it is not), I would rather use a proper lexer generator. It will usually be just as fast, much easier to maintain and much safer.
Two additional things: 1) the stdio API becomes just as verbose as iostreams, if not more so, when you actually do error handling. 2) your code doesn't actually address the OPs original complaint: not being able to work with string objects directly.
<br />This nags at me a bit too: http://stackoverflow...answer-5165293<br />
N.B. If you want to avoid the formatting overhead of fstream, you can shed one layer of abstraction by accessing it's internal filebuf object, though obviously you're now responsible for doing some of the work that the stream used to do for you.

This topic is closed to new replies.

Advertisement