优先使用fstream::operator!()而不是fstream::is_open()(6894)

判断fstream是否可以继续操作应当使用bool operator!() const而不是is_open,因为is_open只表示是否已经打开,而不论其是否正确。

#pragma warning( disable: 4786 )
#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;

int main( void )
{
    ostream_iterator<char> oite( cout );

    ifstream file( "D://test.txt" );
    cout << "文件是否打开:" << boolalpha << bool(file.is_open()) << ' ';
    cout << "文件是否正确:" << boolalpha << !!file << endl;
    {
        file.seekg( 0L, ios::beg );
        istream_iterator<char> fitor( file );
        istream_iterator<char> fend;
        copy( fitor, fend, oite );
        cout << endl;
    }
    cout << "文件是否打开:" << boolalpha << bool(file.is_open()) << ' ';
    cout << "文件是否正确:" << boolalpha << !!file << endl;
    {
        file.seekg( 0L, ios::beg );
        istream_iterator<char> fitor( file );
        istream_iterator<char> fend;
        copy( fitor, fend, oite );
        cout << endl;
    }
    return 0;
}

输出是:
文件是否打开:true 文件是否正确:true
……文件内容……
文件是否打开:true 文件是否正确:false
……本来应该打印文件内容,但因为file不正确了,所以只输出空行……
Press any key to continue

 

 

 

 

PS:

warning C4786错误解决方法:
此warning产生的原因是因为标识符过长,超过了最大限定255个字。

解决方法有两种,一种是直接定义别名:
#ifdef _DEBUG
#define VeryLongClassNameA A
#define VeryLongClassNameB B
#endif

另一种是屏蔽4786warning:
#pragma warning(disable : 4786)

注意屏蔽语句必须放在报错的模板类的引用声明(如#include <vector>)之前,否则还是不起作用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果你不想使用 `std::getline` 函数来读取文件,你可以使用 `std::fstream` 类和 `operator>>` 运算符来逐个字符或逐个单词读取文件内容。 以下是使用 `operator>>` 运算符逐个单词读取文件内容并写入新文件的示例代码: ```c++ #include <iostream> #include <fstream> #include <string> int main() { std::string input_file = "input.txt"; std::string output_file = "output.txt"; // 打开输入文件 std::ifstream fin(input_file); // 检查输入文件是否打开成功 if (!fin.is_open()) { std::cerr << "Failed to open input file: " << input_file << std::endl; return 1; } // 打开输出文件 std::ofstream fout(output_file); // 检查输出文件是否打开成功 if (!fout.is_open()) { std::cerr << "Failed to open output file: " << output_file << std::endl; return 1; } // 逐个单词读取输入文件并写入输出文件 std::string word; while (fin >> word) { fout << word << " "; } // 关闭文件流 fin.close(); fout.close(); std::cout << "File copied successfully!" << std::endl; return 0; } ``` 在这个示例程序中,我们使用 `std::ifstream` 和 `std::ofstream` 类打开输入文件和输出文件。然后,我们使用 `operator>>` 运算符逐个单词读取输入文件中的内容,并将读取到的单词写入输出文件。最后,我们关闭文件流并输出成功消息。 注意,这种方法无法处理空格或制表符等空白字符,因为它只会读取输入流中的非空白字符。如果你需要保留空格或制表符,可以将 `fout << word << " ";` 改为 `fout << word << std::endl;`,这样每个单词都会单独一行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值