C++使用ifstream讀取文件內容的示例詳解
更新時間:2023年03月01日 10:23:49 作者:小小碼農Come on
這篇文章主要為大家詳細介紹了C++如何使用ifstream讀取文件內容的功能,文中的示例代碼講解詳細,具有一定的參考價值,感興趣的可以了解一下
測試文件如下內容:myfile.txt
Fry: One Jillion dollars.
[Everyone gasps.]
Auctioneer: Sir, that's not a number.
數(shù)據讀取, 測試 。
C++中使用ifstream類實現(xiàn)讀文件操作,代碼如下:
實現(xiàn)了:
1、以行讀取文件
2、逐個詞讀取文件
3、文件名正確性檢測
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//讀取整個文件內容到char array數(shù)組中去
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, 將行讀入字符數(shù)組, 行之間用回車換行區(qū)分
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, 行之間用回車換行區(qū)分
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 0
char 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數(shù)組中去
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;
}
到此這篇關于C++使用ifstream讀取文件內容的示例詳解的文章就介紹到這了,更多相關C++ ifstream讀取文件內容內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++實現(xiàn)LeetCode(167.兩數(shù)之和之二 - 輸入數(shù)組有序)
這篇文章主要介紹了C++實現(xiàn)LeetCode(167.兩數(shù)之和之二 - 輸入數(shù)組有序),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-08-08

