EvilZone
Programming and Scripting => C - C++ => : Mellow_ 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?
-
Maybe do a check and see if it read any content and that the last character is the EOF character. Also as far as i could search this is the windows implementation. You could ofc make it cross-platform by adding this extention when it is compiled in linux:
READFILE(3am) GNU Awk Extension Modules READFILE(3am)
NAME
readfile - return the entire contents of a file as a string
SYNOPSIS
@load "readfile"
result = readfile("/some/path")
DESCRIPTION
The readfile extension adds a single function named readfile(). The
argument is the name of the file to read. The return value is a string
containing the entire contents of the requested file.
Upon error, the function returns the empty string and sets ERRNO.
EXAMPLE
@load "readfile"
...
contents = readfile("/path/to/file");
if (contents == "" && ERRNO != "") {
print("problem reading file", ERRNO) > "/dev/stderr"
...
}
-
I'll look around and see if there are any non-windows implementation, but if not I'll definitely use that. Thanks a ton, enjoy the rep.