4
« on: June 11, 2013, 07:14:44 pm »
I have a quick question with reading a file. I'm trying to read a file from the command line with the following:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void readFile(char* file, string& fileContents)
{
fstream fs;
stringstream ss;
fs.open(file,ios::in);
while(fs.good())
ss << static_cast<char>((char)fs.get());
fileContents = ss.str();
fileContents = fileContents.substr(0,fileContents.size()-1);
}
int main(int argc, char* argv[])
{
if(argc != 2) { //Terminate program if zero or more than one arguments provided.
cout << "Usage: " << argv[0] << " <filename>" << endl;
exit(1);
}
char* pFilename = argv[1];
string fileContents;
readFile(pFilename, fileContents);
cout << fileContents;
}
I had problems getting getline() to work with the file I opened, I'm not particularly sure why. So I did this method where I read each charater into a stringstream, make a string equal to the stringstream's contents, and then shave off the last character which is an unnecessary EOF gathered by stringstream. This would break if any unicode was involved.
Any way to make this more elegant or to have getline() work?