带你粗略了解C++流的读写文件

目录
  • 读写文本文件
    • 二进制读写文件
      • 按指定格式读写文件
  • 总结

读写文本文件

C++的IO流:
IO:向设备输入数据和输出数据

设备有:
1)文件
2)控制台
3)特定的数据类型(stringstream)
C++中,必须通过特定的已经定义好的类, 来处理IO(输入输出)

C++的 IO类库为:

文件流:对文件进行读写操作
头文件: < fstream >

ifstream 对文件输入(读文件)
ofstream 对文件输出(写文件)
fstream 对文件输入或输出

文件的打开方式:

模式标志 描述
ios::in 读方式打开文件
ios:out 写方式打开文件
ios::trunc 如果此文件已经存在, 就会打开文件之前把文件长度截断为0
ios::app 尾部最加方式(在尾部写入)
ios::ate 文件打开后, 定位到文件尾
ios::binary 二进制方式(默认是文本方式)

写文本文件

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
	string name;
	int age;
	ofstream outfile;  //也可以使用fstream, 但是fstream的默认打开方式不截断文件长度
	// ofstream的默认打开方式是,  截断式写入 ios::out |  ios::trunc
	// fstream的默认打开方式是,  截断式写入   ios::out
	// 建议指定打开方式
	outfile.open("user.txt", ios::out | ios::trunc);
	while (1) {
		cout << "[ctrl+z退出]" << endl;
		cout << "请输入姓名:";
		cin >> name;
		if (cin.eof()) { //判断文件是否结束
			break;
		}
		outfile << name << "\t";
		cout << "请输入年龄: ";
		cin >> age;
		outfile << age << endl;  //文本文件写入
	}
	// 关闭打开的文件
	outfile.close();
	system("pause");
	return 0;
}

写文本文件

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
	string name;
	int age;
	ifstream infile;
	infile.open("user.txt");
	while (1) {
		infile >> name;
		if (infile.eof()) { //判断文件是否结束
			break;
		}
		cout << name << "\t";
		infile >> age;
		cout << age << endl;
	}
	// 关闭打开的文件
	infile.close();
	system("pause");
	return 0;
}

二进制读写文件

写二进制文件
使用文件流对象的write方法写入二进制数据.

注:若 ***outfile << age << end;***
写入文件会转换到文本方式写入
需要使用write(写)吧整形转换到char类型,进行写入

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
	string name;
	int age;
	ofstream outfile;
	outfile.open("user.dat", ios::out | ios::trunc | ios::binary);
	while (1) {
		cout << "请输入姓名: [ctrl+z退出] ";
		cin >> name;
		if (cin.eof()) { //判断文件是否结束
			break;
		}
		outfile << name << "\t";
		cout << "请输入年龄: ";
		cin >> age;
		//outfile << age << endl;  //会自动转成文本方式写入
		outfile.write((char*)&age, sizeof(age));
	}
	// 关闭打开的文件
	outfile.close();
	system("pause");
	return 0;
}

二进制读文件

需使用read(读)吧写入的内容读取出来并输出

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
	string name;
	int age;
	ifstream infile;
	infile.open("user.dat", ios::in | ios::binary);
	while (1) {
		infile >> name;
		if (infile.eof()) { //判断文件是否结束
			break;
		}
		cout << name << "\t";
		// 跳过中间的制表符
		char tmp;
		infile.read(&tmp, sizeof(tmp));
		//infile >> age; //从文本文件中读取整数, 使用这个方式
		infile.read((char*)&age, sizeof(age));
		cout << age << endl;  //文本文件写入
	}
	// 关闭打开的文件
	infile.close();
	system("pause");
	return 0;
}

按指定格式读写文件

指定格式写文件:
使用 < stringstream>

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
	string name;
	int age;
	ofstream outfile;
	outfile.open("user.txt", ios::out | ios::trunc);
	while (1) {
		cout << "[ctrl+z退出]" << endl;
		cout << "请输入姓名: ";
		cin >> name;
		if (cin.eof()) { //判断文件是否结束
			break;
		}
		cout << "请输入年龄: ";
		cin >> age;
		stringstream s;
		s << "name:" << name << "\t\tage:" << age << endl;
		outfile << s.str();
	}
	// 关闭打开的文件
	outfile.close();
	system("pause");
	return 0;
}

指定格式读文件:
在C++指定格式读文件并没有优雅的解决方案
就用C语言的: sscanf

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <Windows.h>
using namespace std;
int main(void)
{
	char name[32];
	int age;
	string line;
	ifstream infile;
	infile.open("user.txt");
	while (1) {
		getline(infile, line);
		if (infile.eof()) { //判断文件是否结束
			break;
		}
		sscanf_s(line.c_str(), "姓名:%s 年龄:%d", name, sizeof(name),&age);
		cout << "姓名:" << name << "\t\t年龄:" << age << endl;
	}
	infile.close();
	system("pause");
	return 0;
}

文件流的状态检查

描述
is_open() 文件流是否打开成功
eof() 流是否结束
fail() 流的failbit或者badbit被置位时, 返回true
failbit: 出现非致命错误,可挽回, 一般是软件错误 badbit:置位, 出现致命错误, 一般是硬件错误或系统底层错误, 不可挽回
bad() 流的badbit置位时, 返回true
good() 流处于有效状态时, 返回true
clear() 流的所有状态都被复位

文件流的三种定位 seekg tellg seekp

seekg:

seekg( off_type offset, //偏移量
ios::seekdir origin ); //起始位置
作用:设置输入流的位置
参数1: 偏移量
参数2: 相对位置
beg 相对于开始位置
cur 相对于当前位置
end 相对于结束位置

获取文件的最后50个字符:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
	ifstream infile;
	infile.open(/*文件名字这里我就不写了*/".cpp");
	if (!infile.is_open()) {
		return 1;
	}
		//定位到最后50个字母
	infile.seekg(-50, infile.end);
	while (!infile.eof()) {
		string line;
		getline(infile, line);
		cout << line << endl;
	}
	infile.close();
	system("pause");
	return 0;
}

tellg:

返回该输入流的当前位置(距离文件的起始位置的偏移量)

获取文件的长度:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
	ifstream infile;
	infile.open(/*文件名字这里我就不写了*/".cpp");
	if (!infile.is_open()) {
		return 1;
	}
	// 先把文件指针移动到文件尾
	infile.seekg(0, infile.end);
	int len = infile.tellg();
	cout << "len:" << len;
	infile.close();
	system("pause");
	return 0;
}

seekp

设置该输出流的位置

先向新文件写入:“123456789”

然后再在第4个字符位置写入"ABC"

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
	ofstream outfile;
	outfile.open("test.txt");
	if (!outfile.is_open()) {
		return 1;
	}
	outfile << "123456789";
	outfile.seekp(4, outfile.beg);
	outfile << "ABC";
	outfile.close();
	system("pause");
	return 0;
}

常见的错误

1.文件没有关闭, close(),可能导致写文件失败
2.文件打开方式不合适
3.在VS2015的部分版本中,当sscanf和sscanf_s的格式字符串中含有中文时,可能会读取失败。

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注我们的更多内容!

(0)

相关推荐

  • c++读写文件流实例程序讲解

    掌握文本文件读写的方法了解二进制文件的读写方法 C++文件流: 复制代码 代码如下: fstream // 文件流ifstream // 输入文件流ofstream // 输出文件流 //创建一个文本文件并写入信息//同向屏幕上输出信息一样将信息输出至文件#include<iomanip.h>#include<fstream.h>void main(){ ofstream f1("d:\\me.txt"); //打开文件用于写,若文件不存在就创建它 if(!f1

  • C++读写Excel的实现方法详解

    1.导入Excel类型库使用Visual C++的扩展指令#import导入Excel类型库: 复制代码 代码如下: #import "C:\\Program Files\\Common Files\\microsoft shared\\OFFICE14\\MSO.DLL" \     rename("RGB","MsoRGB") \     rename("SearchPath","MsoSearchPath&qu

  • C++读写配置项的基本操作

    读写配置项,在编程当中是非常常用的东西.读写的数据量很小的时候,就没必要用数据库或者Excel之类的东西.今天特意总结下C++.还有Qt读写配置项的操作.其实操作非常简单.废话不多说,下面直接上代码. C++ 写配置项 #include <iostream> #include <windows.h> using namespace std; int main() { // 写配置项 WritePrivateProfileString(L"进程", // 节名称

  • C++实现读写文件的示例代码

    1.读取 1.1逐行读取 void readTxt(string file) { ifstream ifs; ifs.open(file); //将文件流对象与文件关联起来,如果已经关联则调用失败 assert(ifs.is_open()); //若失败,则输出错误消息,并终止程序运行 string s; while(getline(ifs,s)) //行分隔符可以显示指定,比如按照分号分隔getline(infile,s,';') { cout<<s<<endl; } ifs.c

  • C++ 读写文件安全又简洁的简单实例

    C++ 读写文件安全又简洁的简单实例 实例代码: #include <string> #include <iostream> #include <fstream> using namespace std; int get_file_content(string sFileName, string& sFileContent); int main(int argc, char* argv[]) { string sFileContent; get_file_con

  • 带你粗略了解C++流的读写文件

    目录 读写文本文件 二进制读写文件 按指定格式读写文件 总结 读写文本文件 C++的IO流: IO:向设备输入数据和输出数据 设备有: 1)文件 2)控制台 3)特定的数据类型(stringstream) C++中,必须通过特定的已经定义好的类, 来处理IO(输入输出) C++的 IO类库为: 文件流:对文件进行读写操作 头文件: < fstream > ifstream 对文件输入(读文件) ofstream 对文件输出(写文件) fstream 对文件输入或输出 文件的打开方式: 模式标志

  • java使用RandomAccessFile类基于指针读写文件实例代码

    java API中提供了一个基于指针操作实现对文件随机访问操作的类,该类就是RandomAccessFile类,该类不同于其他很多基于流方式读写文件的类.它直接继承自Object. public class RandomAccessFile extends Objectimplements DataOutput, DataInput, Closeable{...} 1.使用该类时可以指定对要操作文件的读写模式. 第一种模式是只读模式,第二种模式是读写模式.在创建该类实例时指定. @Test pu

  • node.js 利用流实现读写同步,边读边写的方法

    如下所示: //10个数 10个字节,每次读4b,写1b let fs=require("fs"); function pipe(source,target) { //先创建可读流,再创建可写流 //先读一次,rs.on(data) //将读到的类容写入目标中 ,返回布尔值,如果是ture,继续写,默认情况应该是false,暂停读取 //ws.on('drain'),抽干后,回复读取 //监听读取文件完毕后,关闭读取rs.on('end') let rs=fs.createReadSt

  • Node.js 使用流实现读写同步边读边写功能

    废话不多说了,直接给大家贴代码了,具体代码如下所示: //10个数 10个字节,每次读4b,写1b let fs=require("fs"); function pipe(source,target) { //先创建可读流,再创建可写流 //先读一次,rs.on(data) //将读到的类容写入目标中 ,返回布尔值,如果是ture,继续写,默认情况应该是false,暂停读取 //ws.on('drain'),抽干后,回复读取 //监听读取文件完毕后,关闭读取rs.on('end') l

  • Java基于字符流形式读写数据的两种实现方法示例

    本文实例讲述了Java基于字符流形式读写数据的两种实现方法.分享给大家供大家参考,具体如下: 第一种方式:逐个字符进行读写操作(代码注释以及详细内容空闲补充) package IODemo; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CopyFileDemo { /** * @param args * @throws IOException */ p

  • Java 如何利用缓冲流读写文件

    利用缓冲流读写文件 从控制台读取数据写入文件 读取文件输出到控制台 public class BookTest { public static void main(String[] args) { //从控制台输入信息并写入文件中 BufferedReader ir=new BufferedReader(new InputStreamReader(System.in)); //包装成字符输入缓冲流 BufferedWriter bw=null; try { bw=new BufferedWrit

  • C#之IO读写文件方法封装代码

    具体不做详细介绍了,直接上代码 /// <summary> /// 功能:FileStream文件流读取文件 /// </summary> /// <param name="filePath">参数:文件路径</param> /// <returns>返回值:StreamReader对象</returns> public static StreamReader ReadFileByFs(string filePat

  • 详解nodeJS中读写文件方法的区别

    导言:nodejs中所有与文件相关的操作都在fs模块中,而读写操作又是我们会经常用到的操作,nodejs的fs模块针对读操作为我们提供了readFile,read, createReadStream三个方法,针对写操作为我们提供了writeFile,write, createWriteStream三个方法,下面分析一下它们的区别: 一.readFile和writeFile 1.readFile方法是将要读取的文件内容完整读入缓存区,再从该缓存区中读取文件内容,具体操作如下: fs.readFil

  • C#读写文件的方法汇总

    1.使用FileStream读写文件 文件头: 复制代码 代码如下: using System;using System.Collections.Generic;using System.Text;using System.IO; 读文件核心代码: 复制代码 代码如下: byte[] byData = new byte[100];char[] charData = new char[1000];try{FileStream sFile = new FileStream("文件路径",F

随机推荐