ostream << istream 并在空文件上测试 EOF,从 istream 获取字符的替代方法



这是我在stackoverflow上的第一篇文章,所以如果我做错了,请告诉我。下周三我要参加c++编程入门的期末考试,但是我没有办法检查教授的练习题的答案。我主要关心的是在将输入文件的内容复制到输出文件之前检查输入文件是否为空。另外,从输入文件中抓取字符。下面是问题和我的代码:

假设我们有以下枚举类型来列出可能的文件I/O错误:

enum FileError {
   NoFileError,       // no error detected
   OpenInputError,    // error opening file for input
   OpenOutputError,   // error opening file for output
   UnexpectedFileEnd, // reached end-of-file at unexpected spot in program
   EmptyFileError,    // file contained no data
};

为以下三个文件处理例程提供适当的实现:

FileError OpenInputFile(ifstream& infile, char *filename);
// open the named file for input, and return the opening status
FileError OpenOutputFile(ofstream& outfile, char *filename);
// open the named file for output, and return the opening status
FileError CopyNChars(ifstream& infile, ofstream& outfile, int NumChars);
// check to ensure the two files are open,
//    then copy NumChars characters from the input file to the output file

现在我主要关注这里列出的最后一个函数。下面是我的代码:

FileError CopyNChars(ifstream& infile, ofstream& outfile, int NumChars){
    char c;
    if (!infile.is_open()) return 1;
    if (!outfile.is_open()) return 2;
    if ((infile.peek()) == -1) return 4; //This right? (I'm using linux with g++ compiler.
    // Also, can I return ints for enum types?
    for (int i = 0; i < NumChars; i++){
        if (infile.eof()) return 3;
        else {
            infile.get(c); //Is this the way to do this?  Or is there another recommendation?
            outfile << c;
        }
    }
}

在阅读之前,我已经查看了检查EOF的各种方法,但我还没有找到-1或EOF是有效检查(类似于NULL??)的具体答案。我认为这只是我对术语不熟悉,因为我看过文档,我找不到这种检查的示例。我在这里做空文件检查正确吗?我没有编写一个驱动程序来测试这段代码。此外,我担心我正在使用的get方法。在这种情况下是否存在其他选择,以及一次获得一个角色的最佳方法是什么。最后,我是否可以问一些关于堆栈溢出的推测性问题(比如"在这种情况下,有什么方法可以获得,什么是最好的?")。感谢您的宝贵时间和考虑。

查看cplusplus.com。它有一些使用ifstream的好例子:http://www.cplusplus.com/reference/fstream/ifstream/

特别是,您可能想要检查没有参数的get()函数。如果命中EOF,则返回EOF。此外,ifstream有一个eof()函数,它将告诉您是否设置了eof位。另外,我不知道是否保证检查peek()的返回值。CSTDIO定义了EOF宏,通常是-1,但我不认为语言能保证。

另外,我将返回enum字面值,而不是返回整数值。

相关内容

最新更新