c++ - C++ 读取文件

标签 c++ file-io stream

我正在尝试编写一个递归函数,它在我为类作业打开的文件中进行一些格式化。这是我到目前为止写的:

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();
}

我的问题出在我的 Reverse() 函数中。那是我一次从文件中读取一个字符的方式吗?谢谢。

最佳答案

你最好使用这个:

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

人们经常忽视的一点是,您可以通过仅测试流对象来简单地测试输入流是否已达到 EOF(或其他一些错误状态)。它被隐式转换为 boolistreams 运算符 bool() 只是调用(我相信)istream::good()

将此与流提取运算符始终返回流对象本身这一事实相结合(以便它可以与多个提取链接,例如“cin >> a >> b”),您将得到非常简洁的语法:

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

更新

抱歉,我没有考虑 - 当然这会跳过空格,这不适用于您反转文件内容的示例。最好坚持使用

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

}

它还返回 istream 对象,允许隐式调用 good()

关于c++ - C++ 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2111474/

相关文章:

java - 如何在 Java 8 Stream Filter 中基于子文档过滤 Mongo 文档

java - 为什么刷新对 System.err 不起作用?

C++ union 的未定义行为

c++ - 当我使用opencv函数cvNorm(image,NULL,CV_L2)时,返回异常结果,为什么?

c++ - 实现多个函数调用是不好的做法吗?

c++ - 如何在循环中表示不再输入字符串 ss while (cin >> ss)

c# - 在文件中搜索字节序列 (C#)

python - 如何将数据随机拆分为训练集和测试集?

c++ - 数组 + union + 包含位字段 C++ 的结构

c++ - 使用 `getline(cin, s);` 后使用 `cin >> n;`