VC读写txt文件

发布时间:2018-06-30 11:55:39

C++读写文本文件

#include
#include

using namespace std;

int main()
{
const char filename[] = "mytext.txt";
ofstream o_file;
ifstream i_file;
string out_text;

//
o_file.open(filename);
for (int i = 1; i <= 10; i++)
{
o_file << "" << i << "\n"; //将内容写入到文本文件中
}
o_file.close();

//
i_file.open(filename);
if (i_file.is_open())
{
while (i_file.good())
{
i_file >> out_text; //将读取的内容存储到变量out_text
cout << out_text << endl; //在控制台输出读取的内容。为什么最后一行的内容会出现两次
}
}
else
cout << "打开文件:" << filename << " 时出错!";
i_file.close();

system("PAUSE");
return 0;
}

为什么总会将最后一行显示两遍?我的循环似乎没错呀。

笔记:C++文件的读取和写入

无论读写都要包含头文件

读:从外部文件中将数据读到程序中来处理
对于程序来说,是从外部读入数据,因此定义输入流,即定义输入流对象:ifsteam infileinfile就是输入流对象。
这个对象当中存放即将从文件读入的数据流。假设有名字为myfile.txt的文件,存有两行数字数据,具体方法:
int a,b;
ifstream infile;
infile.open("myfile.txt"); //注意文件的路径
infile>>a>>b; //两行数据可以连续读出到变量里
infile.close()

如果是个很大的多行存储的文本型文件可以这么读:
char buf[1024]; //临时保存读取出来的文件内容
string message;
ifstream infile;
infile.open("myfile.js");
if(infile.is_open()) //文件打开成功,说明曾经写入过东西
{
while(infile.good() && !infile.eof())
{
memset(buf,0,1024);
infile.getline(buf,1204);
message = buf;
...... //这里可能对message做一些操作
cout<
}
infile.close();
}

写:将程序中处理后的数据写到文件当中
对程序来说是将数据写出去,即数据离开程序,因此定义输出流对象ofstream outfileoutfile就是输出流对象,这个对象用来存放将要写到文件当中的数据。具体做法:
ofstream outfile;
outfile.open("myfile.bat"); //myfile.bat是存放数据的文件名
if(outfile.is_open())
{
outfile<//message是程序中处理的数据
outfile.close();
}
else
{
cout<<"不能打开文件!"<
}


c++对文件的读写操作的例子

/*/从键盘读入一行字符,把其中的字母依次放在磁盘文件fa2.dat中,再把它从磁盘文件读入程序,
将其中的小写字母改成大写字母,再存入磁盘fa3.dat*/
i nclude
i nclude
i nclude
using namespace std;
//////////////从键盘上读取字符的函数
void read_save(){
char c[80];
ofstream outfile("f1.dat");//以输出方工打开文件
if(!outfile){
cerr<<"open error!"<注意是用的是cerr
exit(1);
}
cin.getline(c,80);//从键盘读入一行字符
for(int i=0;c[i]!=0;i++) //对字符一个一个的处理,直到遇到'/0'为止
if(c[i]>=65&&c[i]<=90||c[i]>=97&&c[i]<=122){//保证输入的字符是字符
outfile.put(c[i]);//将字母字符存入磁盘文件
cout<
}
cout<
outfile.close();
}
void creat_data(){
char ch;
ifstream infile("f1.dat",ios::in);//以输入的方式打开文件
if(!infile){
cerr<<"open error!"<
exit(1);
}
ofstream outfile("f3.dat");//定义输出流f3.dat文件
if(!outfile){
cerr<<"open error!"<
exit(1);
}
while(infile.get(ch)){//当读取字符成功时
if(ch<=122&&ch>=97)
ch=ch-32;
outfile.put(ch);
cout<
}
cout<
infile.close();
outfile.close();
}
int main(){
read_save();
creat_data();
system("pause");
return 0;
}

. CStdioFile (MFC类库) 该类由CFile继承而来 (1)打开文本文件 virtual BOOL Open( LPCTSTR lpszFileName, UINT nOpenFlags, CFileException* pError = NULL ); lpszFileName: 路径名 nOpenFlags: 打开方式 ( 常用打开方式: CFile::modeRead Opens the file for reading only. CFile::modeReadWrite Opens the file for reading and writing. CFile::modeWrite Opens the file for writing only. CFile::modeCreate Directs the constructor to create a new file. If the file exists already, it is truncated to 0 length. ) (2)读取文本行 BOOL ReadString(CString& rString); 将读取的文本放在rString.(注意:此时已除去字符串结尾处的换行符'\n') 如果为文件结尾,则返回FALSE (3)写文本行 void WriteString( LPCTSTR lpsz ); (4)获得当前位置(按字节算,即当前指到哪个字节) virtual DWORD GetPosition( ) const; (5)文本定位(按字节算,即当前指到哪个字节) virtual LONG Seek( LONG lOff, UINT nFrom ); ( nFrom: CFile::begin Move the file pointer lOff bytes forward from the beginning of the file. CFile::current Move the file pointer lOff bytes from the current position in the file. CFile::end Move the file pointer lOff bytes from the end of the file. Note that lOff must be negative to seek into the existing file; positive values will seek past the end of the file. ) (6)例子: 输出文本内容 CStdioFile f; CString GFilePath="D:\GeneratorInfo.txt" f.Open(GFilePath,CFile::modeReadWrite); while(f.ReadString(str)) { cout<<(LPCTSTR)str<); //输出格式的设定 file.WriteString(datas); //写数据 file.WriteString("\n"); file.Close(); //写完数据后要将文件关闭 假如z=0,w=10,i=0,jfcha[z][w]=0.00345; 运行程序后,就能在工程目录下,找到一个名为test.txt的文本文件,打开一看,就能看到 jfcha[0][10][0]=3.45*E-3

--------------------------------------

vc++的编程不容易,有时候想实现打开一个文本文件这么简单的功能都挺麻烦的(相对DELPHI),在网上找到一个例子,经修正后列出来。

void CMainFrame::OnFileOpen()
{
//显示文件打开对话框
CFileDialog dlg(TRUE, "SQL", "*.txt",OFN_HIDEREADONLY
|OFN_OVERWRITEPROMPT,"Text Files(*.txt)|*.txt|SQL Files(*.sql)|*.sql|All Files(*.*)|*.*||");
if ( dlg.DoModal()!=IDOK ) return;
//获取文件的绝对路径
CString sFileName=dlg.GetPathName();
//打开文件
CStdioFile out;
out.Open(sFileName, CFile::modeRead);
CString sSql="",s;
//读取文件
do{
out.ReadString(s);
sSql=sSql+s+(char)10;
}
while (out.GetPosition()!=out.GetLength());
out.Close();
AfxMessageBox(sSql);
}

另外还有一个保存的例子,不过还没经过亲自测试:

/*************************************************
* 写文本文件
**************************************************/
//显示文件保存对话框CFileDialog dlg(FALSE, "SQL", "*.txt",OFN_HIDEREADONLY
| OFN_OVERWRITEPROMPT,"Text Files(*.txt)|*.txt|SQL Files(*.sql)|*.sql|All Files(*.*)|*.*||");
if ( dlg.DoModal()!=IDOK ) return;
//获取文件的绝对路径
CString sFileName=dlg.GetPathName();
CStdioFile out;
//打开文件
out.Open(sFileName, CFile::modeCreate | CFile::modeWrite);
//保存文件
CString sSql="文本文件内容";
out.WriteString(sSql);
out.Close();
-----------------------------------------
如何用VC将文本文件中的一列数字读取到数组中

我用下边的程序打开了存有数据的文本文件
CFileDialog dlg(TRUE,"txt","*.txt", //TRUE"打开文件"窗口
OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
"信号数据文件(*.txt)|*.txt|所有文件(*.*)|*.*||",NULL);
if(dlg.DoModal()==IDOK)
{
CString FileName="";
FileName=dlg.GetPathName(); //取文件所在的完整路径
CFile file;
file.Open(FileName,Cfile::modeReadWrite); //以读写方式打开文件
buf1=new char [file.GetLength()]; //为指针动态分配堆栈
file.Read(buf1,file.GetLength()); //将数据读取到内存
m_nData1Len=file.GetLength(); //获取文件长度
file.Close(); //关闭文件
能不能用其中定义的指针char*buf1读出数据
我用A[i]=atof(buf1[i])为什么不能运行
提示错误为 error C2664: 'atof' : cannot convert parameter 1 from 'char' to 'const char *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
请帮忙看看怎么把buf1[i]中的数据读出来.

VC++应用程序中读取文本数据

我们通常把数据存诸在txt文件上,但是我们通常要把这些数据取出来并进行处理。下面我将介绍一种在VC++应用程序中读取文本数据的方法。

一。前言

因为经常要处理地质方面的数据。但是很多数据它不是直接存贮在数据库文件(如Access文件等),而是存贮在txt文件。经常有同学问我怎么通过编程读取实现文本文件中的数据。其实存贮在txt文件也有它的好处,不像读取Access文件那样要注册数据源,设置比较麻烦,编写读取程序也比较复杂。

二。程序原理

首先我们知道假如要进行的文件操作只是简单的读写整行的字符串,那么最好使用CStdioFile,用它来进行此类操作非常方便。因此我们便很自然想到:首先我们把文本文件的每行数据读到一个缓冲区,然后使用sscanf把它转化为字符格式。

那么具体该怎么做呢?比如在一个txt文件里每一行数据格式是这样的:

A1 A2 A3 A3 ……An

那么读取的主体代码是:

CStdioFile File // 定义一个CStdioFile类变量File

CString FileData // 定义一个CString,作为一个缓冲区

/*定义n个临时字符串变量,大小依据实际情况,这里暂设为10

*/

char TempStr1[10]TempStr2[10]……TempStrN[10]

File.ReadStringFileData); // 将一行数据读到缓冲区

/*将该行数据n个字符读到n个临时字符串变量*/

sscanfFileData"%s %s %s %s ……%s"TempStr1TempStr2……TempStrN);

这种读法的一个好处是对文本格式要求不严,如下面的格式也可以(前面可有未知个空格) A1 A2 (两个数据之间也可有未知个空格) A3 A3 ……An

三。编程步骤

下面我以一个单文档程序来具体说明我的做法。该程序的主要功能是读取文本文件的坐标数据,然后在客户区里用直线将这些坐标连起来,并显示。

1 启动Visual C++6.0,生成一个单文档的工程,将该工程命名ReadCoodinate.

2 添加一个读取文本数据的菜单项。

3 给视图类添加两个public变量:

CCPoint> m_Point // 用于记录坐标点数据

int m_PointNum // 用于记录坐标点个数,在视图类构造函数中初始化为0.

4 读取文本数据添加相应的单击消息响应函数。代码如下:

void CReadCoodinateView::OnReaddata()

{

// TODO Add your command handler code here

CFileDialog dlgTRUE); // 定义一个文件对话框变量

ifdlg.DoModal()==IDOK

{

CString m_FilePath = dlg.GetPathName(); //取得文件路径及文件名

CStdioFile File

File.Openm_FilePathCFile::modeRead); //以读模式打开文本文件

CString FileData //定义一个CString变量作为缓冲区

File.ReadStringFileData);//读取第一行数据,第一行数据为坐标点数据

/*定义两个临时字符串,并初始化为'\0'*/

char TempStr1[10]

char TempStr2[10]

memsetTempStr1'\0'10);

memsetTempStr2'\0'10);

sscanfFileData"%s"TempStr1);

m_PointNum = atoiTempStr1); // 获取坐标点个数

/*逐行读取坐标数据*/

for int i = 0ii++

{

File.ReadStringFileData);

sscanfFileData"%s %s"TempStr1TempStr2);

m_Point.AddCPointatoiTempStr1),atoiTempStr2)));//将其存入坐标点数组

}

CDC *pDC = GetDC(); //获取设备环境;

/*根据坐标点绘出直线*/

for i = 0ii++

{

pDC->MoveTom_Point[i].xm_Point[i].y);

pDC->LineTom_Point[i+1].xm_Point[i+1].y);

}

ReleaseDCpDC); //使用完后,释放设备环境

}

}

VC读写txt文件

相关推荐