fstream 中判断是否成功打开文件

EPLAN二次开发实战:从API接口到定制化功能的完整指南 本文为电气工程师和自动化设计师提供了一份EPLAN二次开发的完整实战指南。文章详细介绍了从脚本、插件到独立程序三种开发模式,重点讲解了如何使用C#或VB.NET通过API接口操作EPLAN数据模型,实现定制化功能以提升设计效率,并分享了开发环境搭建、调试及项目打包分发的避坑经验。 阅读详情

from: http://blog.csdn.net/zhtsuc/article/details/2938614


关于C++ fstream的一个容易使用出错的地方

关于c++ 中 文件流的两个类,ifstream 和ofstream,大家也许并不陌生。

其负责c++的文件输入流 和 文件输出流。基本上所以语言都会提供类似的文件输入流 和文件输出流类。

 

但当大家学习了java,或者c#后,大家就很容易用错这个类,把三种语言混淆。

在java 和 c#中,关于打开输入文件流,或者输出流,都是通过抛出异常来标志打开失败。

而且大家对这种思想也很容易接受。

 

所以在c++中如下的错误使用很是常见。

  1. try
  2. {
  3.   ifstream fin("filename");
  4.   //TODO:
  5. }
  6. catch(exception)
  7. {
  8.   cout << "fail to open file" << endl;
  9. }

其实c++的ifstream,ofstream和c#,java的文件流类在这一点上并不相同。

当文件打开失败或者其他错误时,并没有异常抛出。那读者就会想,“如何判断文件打开成功呢”。

因为肯定要确定文件打开成功,才能操作文件流对象。

如下为一般的正确使用方法。

 

  1. ifstream fin("filename");

  2. if (!fin)
  3. {
  4.   cout << "fail to open the file" <<endl;
  5.   return -1;//或者抛出异常。
  6. }
  7. else
  8. {
  9.   cout << "open the file successfully" << endl;
  10. }

这时候有人又有疑问了。fin是一个ifstream对象,不可能是0,或者NULL啊。怎么会有!fin的这个判断语句成功呢。

正如我们所以疑问的,!fin并不是说判断fin是否为0或者为空。而是ifstream类重载了!操作符,所以当我们如此使用的时候,是!操作符函数返回一个bool变量来标记是否成功。

 

类似的对于ofstream也是如此。

 

其实在c++中,很多类都是通过重载操作符来完成一些转化的。读者可以常常留意。


other: http://blog.csdn.net/seadplus/article/details/7802346



四、SVN客户端tortoiseSVN的基本功能介绍 档案浏览器(Repo-browser) 鼠标右键–>tortoiseSVN->版本库浏览器 输入版本库URL地址,进入如菜单界面 版本库浏览器支持SVN及http两种最常用的通信协议 SVN服务器访问方式 方法 模式 访问方法 File:// 直接版本库访问(本地磁盘) http:// 通过配置subversion的WEB服务器的WEBDAV协议 http... 阅读详情

相关推荐

《生化危机9:安魂曲》D加密免BIOS破解方案详解

数字版权管理(DRM)技术通过加密手段保护软件版权,Denuvo(D加密)作为主流方案常应用于3A游戏。其原理是通过实时验证机制阻止未授权访问,但可能影响性能表现。本文以《生化危机9》为例,解析一种免BIOS修改的D加密绕过方案,该方案通过授权启动器模拟正版验证流程,保持系统零侵入性。实测表明,该方法在GTX 1060至RTX 3070等多硬件平台均能稳定运行,支持MOD扩展且兼容Reshade画质增强,为玩家提供开箱即用的绿色版体验。

weixin_33898233的博客 934

关于c++ fstream的一个容易使用出错的地方。

关于c++ 中 文件流的两个类,ifstream 和ofstream,大家也许并不陌生。其负责c++的文件输入流 和 文件输出流。基本上所以语言都会提供类似的文件输入流 和文件输出流类。 但当大家学习了java,或者c#后,大家就很容易用错这个类,把三种语言混淆。在java 和 c#中,关于打开输入文件流,或者输出流,都是通过抛出异常来标志打开失败。而且大家对这种思想也很容易接

随风奔跑的专栏 6017

FP7195升降压恒流驱动IC:从AC/DC 12~24V输入到稳定输出的高效电源设计实战

本文详细解析FP7195升降压恒流驱动IC的工作原理与应用实战。该芯片支持4.5V-32V宽输入范围,能自动切换升降压模式并保持输出恒定,特别适用于车载LED照明、工业电源等电压波动场景。通过实际案例分享PCB布局、元件选型及调试技巧,帮助工程师实现高效稳定的电源设计。

vodka的博客 961

使用fstream读写文件出现读写不成功

使用fstream读写文件出现读写不成功的原因以及正确写入方式

weixin_45914251的博客 1416

Vue3多级路由缓存失效的深度解析与实战解决方案

本文深度解析了Vue3项目中多级路由下keep-alive缓存失效的根本原因,并提供了三种实战解决方案:通过路由扁平化根治问题、利用状态管理精细模拟缓存效果,以及借助keep-alive-vue3插件快速修复。文章旨在帮助开发者彻底理解Vue Router与keep-alive的协作机制,从而根据项目情况选择最佳策略,有效解决页面状态丢失的难题。

weixin_29015801的博客 288

中标麒麟,postgres报错invalid value for parameter "timeZone":"Asia/Beijing"

在中标麒麟服务器上,安装postgres,启动tomcat容器时,报invalid value for parameter "timeZone":"Asia/Beijing"。 查看postgres运行日志,也报同样的错误。 报错原因:服务器的时区,在Postgres支持的时区目录中找不到。当时在服务器上信息为Beijing 解决步骤: 1. cat /etc/sysconfig/cloc

u010213931的博客 7929

C++ fstream的read和write读写文件是提示异常0xc0000005:读取位置0xFFFFFFFFFFFFFFFF 时发生访问冲突,可能的问题

C++ fstream的read和write读写文件是提示异常0xc0000005:读取位置0xFFFFFFFFFFFFFFFF 时发生访问冲突,可能的问题

weixin_45391503的博客 1921

lammps案例:reaxff势模拟Fe(OH)3高温反应过程

所有的reaxff模拟,如:氧化、腐蚀、热裂解、燃烧等模拟,均可采用此模拟框架,只需要更换data文件、势文件,代码中的control文件可以不写,电荷平衡文件也可以用reaxff替换。该案例主要模拟Fe(OH)3在高温下的反应过程,主要代码来自lammps自带的案例。lammps自带案例没有产物输出,故在此基础上稍加修改,增加了产物输出命令。如果需要系统学习反应势的模拟,可考虑报名培训课程。本文分享一个reaxff反应势的案例。in文件代码已经注释,以供参考。大家好,我是小马老师。

lammps_jiayou的博客 1966

异常处理--C++

异常处理 异常处理对于编写健壮的软件来说无疑是非常重要的,是否有完善的异常处理机制也是评价某一程序设计语言优劣的一个重要标准。 总的来说,对于小型程序和大型程序出现异常时,其处理的思想和方法稍有差别。一般来说,当小型程序在出现异常时,则将程序立即中断运行,无条件释放所有资源;对于大型程序,则沿着函数等调用的逻辑关系,逆向回溯报告错误。 基本思想是:在底层(执行层)发现的问题,逐级上报,直到有能力可...

Lapland的博客 414

Python爬虫逆向案例:某云片滑块验证码分析-滑动验证码

今天我们看个滑块。

2201_76125393的博客 1042

基于本机知识库 + 豆包(火山引擎)+ MCP的落地方案

最小 MVP:本地知识库 + Doubao Embedding + 简单检索。工具化:把检索/写入/系统功能通过 MCP 封装。Agent 编排:RAG 流程 + 自检 + 引用输出。这样你就可以快速落地一个基于豆包 + 本机知识库的 MCP Agent。

lpfasd123的博客 1109

fstream的使用问题

//问题十八: //使用fstream对象时,先读再写就会出问题,需要流指针重新定位才能写。先写再读没有问题,流指针会自动右移一位再读 #include #include using namespace std; int main() { fstream stream("hello.txt"); if(!stream) { cerr exit(-1); } cha

享受开发技术,享受计算机科学 835

RK3568平台(USB篇)USB基础知识

现象:把USB设备比如Android手机接到PC答1:是USB控制器,是USB控制器内嵌的root hub.答2. windows里已经有了USB的总线驱动程序,接入USB设备后,是"总线驱动程序"知道你是"android phone"提示你安装的是"设备驱动程序"。USB总线驱动程序负责:识别USB设备, 给USB设备找到对应的驱动程序。答3. PC的USB口内部,D-和D+接有15K的下拉电阻,未接USB设备时为低电平USB设备的USB口内部,D-或D+接有1.5K的上拉电阻;

weixin_49303682的博客 1661

fstream 中判断是否成功打开文件 | C++中文件流(fstream)的使用方法及示例

ifstream fin("filename"); if (!fin) { cout &lt;&lt; "fail to open the file" &lt;&lt;endl; return -1;//或者抛出异常。 } else { cout &lt;&lt; "open the file successfully" &lt;&lt; endl; } 文件流参考链接

专注于AI领域前沿技术学习与分享:目标检测、图像修复、超分重建、AI工程化 4475

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

用Fstream读写文件

用fstream类来读取txt文本文件 fstream有两个子类,ifstream和ofstream,分别用于从硬盘读入数据到内存和把数据从内存写入硬盘。 读: 首先要包含fstream头文件 再定义变量 例 ifstream inputfile ; //inputfile是这个变量的名字 inputfile.open(“文件名”); //调用ifst...

C5DN_的博客 1250

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

C++判断文件是否存在

#include<fstream> #incude<iostream>boolbFileExist=false; std::fstream_file; _file.open(strFilePath,std::ios::in);if(_file)bFileExist=true; _file.close(); ...

weixin_33889665的博客 575

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【千律】C++基础:判断文件是否读取到末尾,判断文件是否读取和写入成功。

#include <fstream> #include <iostream> #include <stdlib.h> using namespace std; int main() { // 初始化 ifstream iread_txt; // 初始化输入流 ofstream write_txt; // 初始化输出流 char* words = "Hello, world!"; .

weixin_42704093的博客 5835

【C++入门】文件流(fstream)介绍和使用

(1)在C++11标准时,open函数的文件路径可以传char指针也可以传string指针,而在C++98标准,open函数的文件路径只能传char指针;(2)open函数的第二个参数是打开文件的模式,从函数定义可以看出,如果调用open函数时省略mode模式参数,则默认按照可读可写(ios_base:in | ios_base::out)的方式打开;(3)打开文件时的mode的模式是从内存的角度来定义的,比如:in表示可读,就是从文件读数据往内存读写;out表示可写,就是把内存数据写到文件中;

weixin_42031299的博客 1万+

C++打开文件的两种方式概述

1.ifstream 类为例,通过 open 成员函数打开 注意到在流对象上执行 open 成员函数,给出文件名和打开模式,就可以打开文件。 判断文件打开是否成功,可以看“对象名”这个表达式的值是否为 true,如果为 true,则表示文件打开成功。 源码如下: #include <iostream> #include <fstream> using namespace std; int main() { ifstream inFile; inFile.open("D

dongbao520的博客 1万+

fstream、ifstream、ofstream

文件流 ofstream //文件写操作,内存写入存储设备(文件) 输出流 通常我们所说的对一个文件进行写操作,就是把内存里的内容,也就是缓冲区的内容写到硬盘,可以将标准输出设备理解为显示器 ifstream //文件读操作,存储设备到内存. 输入流 通常我们所说对一个文件读操作,就是把存在硬盘的内容写到内存中,也就是缓冲区 fstream //读写...

苦逼的程序猿 2756

linux打开文件int open,C++ open 打开文件(含打开模式一览表)

在对文件进行读写操作之前,先要打开文件。打开文件有以下两个目的:通过指定文件名,建立起文件和文件流对象的关联,以后要对文件进行操作时,就可以通过与之关联的流对象来进行。指明文件的使用方式。使用方式有只读、只写、既读又写、在文件末尾添加数据、以文本方式使用、以二进制方式使用等多种。打开文件可以通过以下两种方式进行:调用流对象的 open 成员函数打开文件。定义文件流对象时,通过构造函数打开文件。使用...

weixin_35786770的博客 909

STL fstream使用技巧与分析

fstream 读取文本文件完整代码 首先,展示一下使用fstream读取文本文件的基本代码。 1 #include <string.h> //strerror函数 2 #include <errno.h> //errno错误代码变量 3 #include <fstream> 4 #include <iostream> ...

weixin_33800463的博客 403

C++语法基础--标准IO库--文件的输入和输出(fstream,ifstream,ofstream)

1.fstream   *构造函数:      default (1):             fstream();      initialization (2) :           explicit fstream (const char* filename,ios_base::openmode mode = ios_base::in | ios_base::out);

piniheaven的专栏 1332

C++文件IO

文件IO类 头文件fstream定义了三种类型来支持文件 IO,ifstream从一个给定的文件读取数据,ofstream向一个给定文件写入数据,fstream可以读写给定文件,当文件流对象被销毁时,会自动关闭绑定的文件。 int main(void) { //创建一个未绑定的文件流 std::fstream file1; std::ifstream file2; std::ofstrea...

天道酬勤 1250
上一篇: getline 细节
下一篇: 判断输入的EOF
fruitz
博客等级 码龄12年 2粉丝 5原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值