C++ I/O文件读写操作的示例代码

2020-06-10 12:00:40于丽

读取当前程序的最后50个字符

#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(-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;
}

计算机英语

ioinput output的简写
输出输出
iosC++ 输出输出流的基类
stream流
istream输入流
ostream输出流
iostream输出输出流
fstreamfile stream的简写 文件流
ifstream文件输入流
ofstream文件输出流
stringstream字符串流
istringstream字符串输入流
ostringstream字符串输出流
seek寻找
seekg 设置输入流的位置
seekp设置输出流的位置
tell告诉
tellg返回当前流的位置
open打开
is_open是否打开成功
eofend of file的简写
文件结束
good好的
bad坏的
fail失败

常见错误总结

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

到此这篇关于C++ I/O文件读写操作的示例代码的文章就介绍到这了,更多相关C++ I/O文件读写操作内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!