这篇“C++怎么使用ifstream读取文件内容”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“C++怎么使用ifstream读取文件内容”文章吧。
测试文件如下内容:myfile.txt
Fry: One Jillion dollars.
[Everyone gasps.]
Auctioneer: Sir, that's not a number.
数据读取, 测试 。
C++中使用ifstream类实现读文件操作,代码如下:
实现了:
以行读取文件
逐个词读取文件
文件名正确性检测
#include <iostream>#include <fstream>#include <string>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] = '\0';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 << "] :"<<str<<endl;}cout << "file has line:" << lineNum << endl;}//读取方式:逐行读取Line by Line, 将行读入string, 行之间用回车换行区分void fileReadToString(){std::ifstream file("myfile.txt");int lineNum = 0;string str;while (getline(file, str)) {cout << "Read Data on Line:[" << ++lineNum<<"] :" << str <<endl;}cout << "file has line:" << lineNum << endl;}//读取方式:逐词读取Word by Word,词之间用空格划分void fileReadWbW(){std::ifstream file("myfile.txt");string s;while (file >> s){cout << "Read From File[" << s <<"]"<<endl;}}//带检测文件名功能void fileReadWithErrCheck(){string fileName = "file .dat";std::ifstream fin(fileName.c_str());if (!fin) {cout << "Error Opening file:[" << fileName << "]" << " for input " << endl;exit(-1);}}int main(){#if 0char data[100];ofstream outfile;outfile.open("myfile.txt", ios::out | ios::trunc);cout << "enter your name: ";//cin.getline(data, 100);outfile << "hello world"<<endl;ifstream infile;infile.open("myfile.txt", ios::in);cout << "read file from myfile.txta" << endl;string readData;infile >> readData;std::cout << "data:" << readData << endl;outfile.close();#endif//读取整个文件内容到char array数组中去fileReadAllToCharArray();std::cout << "-----------------" << endl;//逐行读取Line by LinefileReadToCharArray();std::cout << "-----------------" << endl;//文件逐词读取Word by WordfileReadWbW();std::cout << "-----------------" << endl;//逐行读取Line by Line, 将行读入string分fileReadToString();//带检测文件名功能fileReadWithErrCheck();std::cout << "-----------------" << endl;}
以上就是关于“C++怎么使用ifstream读取文件内容”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注编程网行业资讯频道。