jjzjj

c++文件输入输出流fstream指定文件路径正确书写

芯辰大海 2023-12-14 原文

目录

正确打开文本文件

读取文本文件并打印输出

字符数组方式读取并打印输出

字符串方式读取并打印输出


正确打开文本文件

在从文件读取信息或者向文件写入信息之前,必须先打开文件。ofstreamfstream 对象都可以用来打开文件进行写操作,如果只需要打开文件进行读操作,则使用 ifstream 对象。

open() 成员函数的第一参数指定要打开的文件的名称和位置,第二个参数定义文件被打开的模式。(ios::in——打开文件用于读取;ios::out——打开文件用于写入);

1、直接复制文件路径读取文件流(❌错误的,无法读取成功)

fstream  afile;
//afile.open("E:\C++\test", ios::out | ios::in); 复制test的路径只会复制到文本test的上一层
afile.open("E:\C++\test\test.txt", ios::out | ios::in); //这是test.txt正确路径


2、fstream文件流读取,路径名中的斜杠要双写,如:
"D:\\MyFiles\\ReadMe.txt"

fstream  afile;
afile.open("E:\\C++\\test\\test.txt", ios::out | ios::in);

而且命名为test.txt的文本文件,正确书写路径如下;

fstream  afile;
afile.open("E:\\C++\\test\\test.txt.txt", ios::out | ios::in);

3、读取下面这个文件完整测试代码;

#include<iostream>
using namespace std;
#include<fstream>
int main() {
	fstream  afile;
	afile.open("E:\\C++\\test\\test.txt.txt", ios::out | ios::in);
	if (afile.is_open()) {
		cout << "file open success !" << endl;
	}
	else
	{
		cout << "file open erro!" << endl;
	}
	afile.close();
	return 0;
}

注意:对比下面两个文本文件信息;

读取文本文件并打印输出

getline按行读取,字符数组方式读取并打印输出

#include<iostream>
using namespace std;
#include<fstream>
int main() {
	fstream  afile;
	afile.open("E:\\C++\\test\\test.txt.txt", ios::out | ios::in);
	if (afile.is_open()) {
		cout << "file open success !" << endl;
	}
	else
	{
		cout << "file open erro!" << endl;
	}
	//逐行读取文件并打印输出
	char buf[20] = { 0 };
	while (afile.getline(buf,sizeof(buf)))
	{
		cout << buf << endl;
	}

	afile.close();
	return 0;
}

getline按行读取,字符串方式读取并打印输出

需要添加头文件:#include<string>

#include<iostream>
using namespace std;
#include<fstream>
#include<string>
int main() {
	fstream  afile;
	afile.open("E:\\C++\\test\\test.txt.txt", ios::out | ios::in);
	if (afile.is_open()) {
		cout << "file open success !" << endl;
	}
	else
	{
		cout << "file open erro!" << endl;
	}
	//逐行读取文件并打印输出
	string s;
	while (getline(afile,s))
	{
		cout << s << endl;
	}

	afile.close();
	return 0;
}

输出结果:

eof( )读取文本文件内容

test.txt文本内容如下:

读取test.txt并打印输出(没有getline()——读取到空格停止,然后就打印输出)——会发现test.txt最后行的内容会多输出一遍;

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
	string str;
	ifstream fin("F:\\C++\\test.txt");
	//做文本文件操作之前,先判断是否打开成功
	if (fin.is_open()) {
		cout << "file open success !" << endl;
	}
	else
	{
		cout << "file open erro!" << endl;
	}
	if (fin.peek() == EOF)
	{
		cout << "file is empty." << endl;
		return 0;
	}

	while (!fin.eof())
	{
		fin >> str;
		cout << str << endl;
	}
	system("pause");
	return 0;
}

读取test.txt并打印输出(使用getline()逐行读取)——会发现多打印一行空行

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
	string str;
	ifstream fin("F:\\C++\\test.txt");
	//做文本文件操作之前,先判断是否打开成功
	if (fin.is_open()) {
		cout << "file open success !" << endl;
	}
	else
	{
		cout << "file open erro!" << endl;
	}
	if (fin.peek() == EOF)
	{
		cout << "file is empty." << endl;
		return 0;
	}

	while (!fin.eof())
	{
		getline(fin,str);
		cout << str<<endl;
	}
	system("pause");
	return 0;
}

注意:
getline()介绍

eof( )介绍

  • 使用C/C++读文件的时候,eof()这个函数用来判断文件是否为空或者是否读到文件结尾;
  • 事实上fstream流的eof()判断有点不合常理, 按常理逻辑来说,如果到了文件末尾的话,eof()应该返回true,但是,eof在读取完最后一个数据后,仍是False,当再次试图读一个数据时,由于发现fin没数据可读了,才知道到末尾了,此时才修改标志,eof变为True;
  • C++输入输出流如何知道是否到末尾了呢? 解释如下

原来根据的是:如果fin>>不能再读入数据了,才发现到了文件结尾,这时才给流设定文件结尾的标志,此后调用eof()时,才返回真。

假设

    find>>x;  //此时文件刚好读完最后一个数据(将其保存在x中)

    但是,这时fin.eof()仍为false,因为 fin流的标志eofbit是False,fin流此时认为文件还没有到末尾,只有当流再次读写时 fin>>x ,发现已无可读写数据,此时流才知道到达了结尾,这时才将标志eofbit修改为True,此时流才知道文件到了末尾。

  • 因此,读文件时,用while (!fin.eof())结束会导致输出一行空行或将文本文件最后一行内容输出两次(如上述测试代码);
  • 因为文件指针到最后一个字符时并不会触发 eof, 再读一次读不到数据才触发eof, 这样字符串x还保留着上一次的数据,又被输出一次;
  • peek()方法是读取文件指针下一个位置的值,但并不移动文件指针:将while (!fin.eof()) 改为:while (fin.peek()!=EOF)就可避免test.txt最后一行输出两次

peek()!=EOF介绍

  • 把eof()改为 peek() == EOF 来判别,其中peek()是取文件当前指针,EOF是文件尾尾标符,它的值为-1,所以采用这种方法就解决上面eof()的问题
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
	string str;
	ifstream fin("F:\\C++\\test.txt");
	//做文本文件操作之前,先判断是否打开成功
	if (fin.is_open()) {
		cout << "file open success !" << endl;
	}
	else
	{
		cout << "file open erro!" << endl;
	}
	if (fin.peek() == EOF)
	{
		cout << "file is empty." << endl;
		return 0;
	}

	while (fin.peek() != EOF)
	{
		getline(fin,str);
		cout << str<<endl;
	}
	system("pause");
	return 0;
}

有关c++文件输入输出流fstream指定文件路径正确书写的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  8. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  9. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  10. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

随机推荐