开发者

Reading from a file in C++

开发者 https://www.devze.com 2022-12-17 12:20 出处:网络
I\'m trying to write a recursive function that does some formatting within a file I open for a class assignment.This is what I\'ve written so far:

I'm trying to write a recursive function that does some formatting within a file I open for a class assignment. This is what I've written so far:

const char * const FILENAME = "test.rtf";

void OpenFile(const char *fileName, ifstream &inFile) {
    inFile.open(FILENAME, ios_base::in);
    if (!inFile.is_open()) {
        cerr << "Could not open file " << fileName << "\n";
        exit(EXIT_FAILURE);
    }
    else {
        cout << "File Open successful";
    }
}


int Reverse(ifstream &inFile) {
    int myInput;
    while (inFile != EOF) {
        myInput = cin.get();
    }
}

int main(int argc, char *argv[]) {
    ifstream inFile;             // create ifstream file object
    OpenFile(FILENAME, inFile);  // open file, FILENAME, with ifstream inFile object
    Reverse(inFile);          // reverse lines according to output using infile object
    inFile.close();
}

The question I have is in my Reverse() function. Is that how I would read in one character at a time 开发者_Python百科from the file? Thanks.


You'd be better off using this:

char Reverse(ifstream &inFile) {
    char myInput;
    while (inFile >> myInput) {
     ...
    }
}

It's often overlooked that you can simply test whether an input stream has hit EOF (or some other bad state) by just testing the stream object. It's implicitly converted to a bool, and an istreams operator bool() simply invokes (I believe) istream::good().

Combine this with the fact that the stream extraction operator always returns the stream object itself (so that it can be chained with multiple extractions, such as "cin >> a >> b") and you arrive at the very succinct syntax:

while (stream >> var1 >> var2 /* ... >> varN */) { }

UPDATE

Sorry, I'm not thinking - of course this will skip whitespace, which won't work for your example of reversing the contents of a file. Better off sticking with

char ch;
while (inFile.get(ch)) {

}

which also returns the istream object, allowing the implicit call to good().


void Reverse(ifstream &inFile) {
    char myInput;
    while ( inFile.get( myInput ) ) {
       // do something with myInput
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号