0
点赞
收藏
分享

微信扫一扫

C++读写文本文件


首先看看C++中读写文本文件的基本知识:

C++简单读写文本文件

fstream提供了三个类,用来实现C++对文件的操作。
fstream  打开文件供读写
ofstream  向文件写入内容
ifstream  从已有的文件读

文件打开模式
ios::in  读
ios::out  写
ios::app  行文件末尾
ios::binary  二进制模式
ios::nocreate  打开一个文件时,如果文件不存在,不创建文件。
ios::noreplace  打开一个文件时,如果文件不存在,创建该文件。
ios::trunc  打开一个文件,然后清空内容。
ios::ate  打开一个文件时,将位置移动到文件尾。

文件指针位置在C++中的用法:
ios::beg  文件头
ios::end  文件尾
ios::cur  当前位置
主要在seekg()函数中使用

常用的错误判断方法:
good()如果文件打开成功
bad()打开文件时发生错误
eof()到底文件尾

看一个写文件的实例:

void TextFileWrite()
{
ofstream out;
out.open("letter.txt",ios::trunc);//iso::trunc表示在打开文件前将文件清空,由于是写入,文件不存在则创建
char a = 'a';
for (int i = 1; i <= 26; i++)
{
if (i < 10)
{
out<<"0"<<i<<"\t"<<a<<"\n";
}
else
{
out<<i<<"\t"<<a<<"\n";
}
a++;
}
out.close();
}


读文件的实例:

一个字符一个字符地读:

void TextFileRead()
{
fstream in;
char ch;
in.open("letter.txt",ios::in);
while (!in.eof())
{
in>>ch;
cout<<ch;
cout<<'\n';
}
in.close();
}

一行一行地读:


void TextFileReadByLine()
{
char buffer[256];
ifstream in;
in.open("letter.txt",ios::in);
while(!in.eof())
{
//表示该行字符达到256个或遇到换行就结束
in.getline(buffer,256,'\n');
cout<<buffer<<endl;
}
in.close();
}



举报

相关推荐

0 条评论