一、從C讀取txt文件每一行
C語言提供的文件操作函數可以很方便地讀取文本文件。
#include<stdio.h>
int main()
{
FILE *fp;
char buffer[1024];
int index = 0;
fp = fopen("test.txt","r");
if(fp == NULL)
return -1;
while(fgets(buffer,sizeof(buffer),fp) != NULL)
{
printf("Line %d : %s",index+1,buffer);
index++;
}
fclose(fp);
return 0;
}
代碼解析:
① 首先打開文本文件,以只讀方式讀取,如果文件不存在或沒有讀取權限,會返回-1。
② 使用fgets函數逐行讀取文本內容,讀取到文本末尾為NULL。
③ 每次讀取一行後,打印當前行號和內容。
④ 關閉文件句柄,釋放資源。
二、C++讀取txt文件選取3~5個與C讀取txt文件每一行相關的做為小標題
C++也提供了文件操作的標準庫,使用起來更加便捷。
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main()
{
ifstream in("test.txt");
string line;
vector<string> titles;
while(getline(in, line))
{
titles.push_back(line);
if(titles.size() == 5)
break;
}
for(int i = 0; i < titles.size(); i++)
cout << "<h3>" << titles[i] << "</h3><br/>" << endl;
in.close();
return 0;
}
代碼解析:
① 打開文本文件,以輸入流方式讀取。
② 使用getline函數逐行讀取文本內容,每讀取一行就將其作為一個小標題保存到字符串容器中。
③ 如果小標題數量達到5個,則退出循環。
④ 遍歷小標題容器,輸出每個小標題作為html的h3標籤。
⑤ 關閉文件流,釋放資源。
三、C++讀取txt文件每一行的內容
C++標準庫提供了多種讀取文件的方式,我們可以選擇getline或者fstream::read函數來讀取文本文件的內容。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream in("test.txt");
string line;
while(getline(in, line))
cout << line << endl;
in.close();
return 0;
}
代碼解析:
① 打開文本文件,以輸入流方式讀取。
② 使用getline函數逐行讀取文本內容,將每行內容直接輸出。
③ 關閉文件流,釋放資源。
fstream::read函數讀取文本內容的方式:
#include<iostream>
#include<fstream>
using namespace std;
inline int get_count(ifstream& in)
{
in.seekg(0, std::ios_base::end);
return in.tellg();
}
int main()
{
ifstream in("test.txt",ios_base::binary);
int count = get_count(in);
char* buffer = new char[count];
in.seekg(0, ios_base::beg);
in.read(buffer, count);
cout << buffer << endl;
delete [] buffer;
in.close();
return 0;
}
代碼解析:
① 打開二進制文件,以輸入流方式讀取。
② 獲取文件總長度。
③ 開闢一個char類型數組,並將其長度設置為文件總長度。
④ 將文件指針定位到文件頭部,並將文件內容都讀入到char類型數組中。
⑤ 將數組中的內容輸出到控制台。
⑥ 釋放動態開闢的內存,關閉文件流。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/256379.html
微信掃一掃
支付寶掃一掃