文档详情

c对txt文件的读取与写入源代码.doc

发布:2018-05-14约8.98千字共11页下载文档
文本预览下载声明
c++对txt文?件的读取与?写入 /* 这是自己写?程序时突然?用到这方面?的技术,在网上搜了?一下,特存此以备?后用~ */ #inclu?de iostr?eam #inclu?de ioman?ip #inclu?de fstre?am using? names?pace std; int main(){ char buffe?r[256]; ifstr?eam myfil?e (c:\\a.txt); ofstr?eam outfi?le(c:\\b.txt); if(!myfil?e){ cout Unabl?e to open myfil?e; exit(1); // termi?nate with error? } if(!outfi?le){ cout Unabl?e to open otfil?e; exit(1); // termi?nate with error? } int a,b; int i=0,j=0; int data[6][2]; while? (! myfil?e.eof() ) { myfil?e.getli?ne (buffe?r,10); sscan?f(buffe?r,%d %d,a,b); couta bendl; data[i][0]=a; data[i][1]=b; i++; } myfil?e.close?(); for(int k=0;ki;k++){ outfi?ledata[k][0] data[k][1]endl; coutdata[k][0] data[k][1]endl; } outfi?le.close?(); retur?n 0; } 无论读写都?要包含fstre?am头文件 读:从外部文件?中将数据读?到程序中来?处理 对于程序来?说,是从外部读?入数据,因此定义输?入流,即定义输入?流对象:ifste?am infil?e,infil?e就是输入?流对象。 这个对象当?中存放即将?从文件读入?的数据流。假设有名字?为myfi?le.txt的文?件,存有两行数?字数据,具体方法: int a,b; ifstr?eam infil?e; infil?e.open(myfil?e.txt); //注意文件的?路径 infil?eab; //两行数据可?以连续读出?到变量里 infil?e.close?() 如果是个很?大的多行存?储的文本型?文件可以这?么读: char buf[1024]; //临时保存读?取出来的文?件内容 strin?g messa?ge; ifstr?eam infil?e; infil?e.open(myfil?e.js); if(infil?e.is_op?en()) //文件打开成?功,说明曾经写?入过东西 { while?(infil?e.good() !infil?e.eof()) { memse?t(buf,0,1024); infil?e.getli?ne(buf,1204); messa?ge = buf; ...... //这里可能对?messa?ge做一些?操作 coutmessa?geendl; } infil?e.close?(); } 写:将程序中处?理后的数据?写到文件当?中 对程序来说?是将数据写?出去,即数据离开?程序,因此定义输?出流对象o?fstre?am outfi?le,outfi?le就是输?出流对象,这个对象用?来存放将要?写到文件当?中的数据。具体做法: ofstr?eam outfi?le; outfi?le.open(myfil?e.bat); //myfil?e.bat是存?放数据的文?件名 if(outfi?le.is_op?en()) { outfi?lemessa?geendl; //messa?ge是程序?中处理的数?据 outfi?le.close?(); } else { cout不能打开文?件!endl; } c++对文件的读?写操作的例?子 /*/从键盘读入?一行字符,把其中的字?母依次放在?磁盘文件f?a2.dat中,再把它从磁?盘文件读入?程序, 将其中的小?写字母改成?大写字母,再存入磁盘?fa3.dat中*/ #i nclud?efstre?am #i nclud?eiostr?eam #i nclud?ecm
显示全部
相似文档