2013-04-18 52 views
0

这是我在stackoverflow上的第一篇文章,所以如果我做错了,请告诉我。我在下周三的星期三对C++程序设计介绍进行了期末考试,我无法检查我对教授实践问题的答案。我主要关心的是在将其内容复制到输出文件之前检查输入文件是否为空。另外,从输入文件中抓取字符。这里的问题,我下面的代码:ostream << istream和在一个空文件上测试EOF,用于从istream获取字符的替代方法

假设我们有以下的枚举类型,列出可能的文件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方法。在这种情况下是否有其他选择,以及一次获得一个角色的最佳方式是什么?最后,我允许提出有关堆栈溢出的推测性问题(比如“什么是各种获取方法以及这种情况下最好的方法?”)。感谢您的时间和考虑。

+0

把你的阅读状况。 – chris 2013-04-18 02:16:37

+0

嗨@Robertson我知道这是一个错误的地方问,你能帮我把LDAP配置为GitLab吗? – Loganathan 2015-03-31 12:18:47

+0

@loganathan当然可以。 gmail dot com上的aubrey dot viu – 2015-03-31 16:34:13

回答

0

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

特别是,你可能想看看没有参数的get()函数。如果EOF被击中,它会返回EOF。另外,ifstream有一个eof()函数,告诉你他是否设置了eof位。另外,我不知道你的peek()的返回值是否有保证。 CSTDIO定义了EOF宏,通常是-1,但我不认为它是由语言保证的。

此外,而不是返回整数值,我会返回枚举文字。这就是他们在那里。