一、从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/n/256379.html
微信扫一扫
支付宝扫一扫