验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

C++怎么使用ifstream读取文件内容

阅读:796 来源:乙速云 作者:代码code

C++怎么使用ifstream读取文件内容

测试文件如下内容:myfile.txt

Fry: One Jillion dollars.
 [Everyone gasps.]
 Auctioneer: Sir, that's not a number.
 数据读取, 测试 。

C++中使用ifstream类实现读文件操作,代码如下:

实现了:

1、以行读取文件

2、逐个词读取文件

3、文件名正确性检测

#include 
#include 
#include 

using namespace std;

//读取整个文件内容到char array数组中去
void fileReadAllToCharArray()
{
	std::ifstream file;
	//以只读方式打开文件
	file.open("myfile.txt", std::ios::in);

	//指针定位到文件末尾
	file.seekg(0, std::ios::end);
	int fileLength = file.tellg();

	//指定定位到文件开始
	file.seekg(0, std::ios::beg);

	cout << "fileLength:" << fileLength << endl;
	char* buffer = new char[fileLength + 1];
	file.read(buffer, fileLength);
	buffer[fileLength] = '';
	string contents = buffer;
	cout << "contents:" << contents << endl;

	if (buffer) {
		delete[] buffer;
	}
	file.close();
}

//读取方式:逐行读取Line by Line, 将行读入字符数组, 行之间用回车换行区分
void fileReadToCharArray()
{
	std::ifstream file("myfile.txt");
	
	constexpr int LINE_LENGTH = 100;
	char str[LINE_LENGTH];

	int lineNum = 0;
	while (file.getline(str, LINE_LENGTH))
	{
		cout << "Read from line[" << ++lineNum << "] :"<> s)
	{
		cout << "Read From File[" << s <<"]"<> readData;
	std::cout << "data:" << readData << endl;
	outfile.close();
#endif

	//读取整个文件内容到char array数组中去
	fileReadAllToCharArray();
	std::cout << "-----------------" << endl;

	//逐行读取Line by Line
	fileReadToCharArray();
	std::cout << "-----------------" << endl;

	//文件逐词读取Word by Word
	fileReadWbW();
	std::cout << "-----------------" << endl;

	//逐行读取Line by Line, 将行读入string分
	fileReadToString();

	//带检测文件名功能
	fileReadWithErrCheck();
	std::cout << "-----------------" << endl;
}
分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>