在C语言中写文件
FILE *pFile = fopen("1.txt", //打开文件的名称 "w"); // 文件打开方式 如果原来有内容也会销毁 //向文件写数据
fwrite ("hello", //要输入的文字 1,//文字每一项的大小 以为这里是字符型的 就设置为1 如果是汉字就设置为4 strlog("hello"), //单元个数 我们也可以直接写5 pFile //我们刚刚获得到的地址 );
//fclose(pFile); //告诉系统我们文件写完了数据更新,但是我们要要重新打开才能在写
fflush(pFile); //数据刷新 数据立即更新
在C语言中读文件
FILE *pFile=fopen("1.txt","r"); //获取文件的指针 char *pBuf; //定义文件指针 fseek(pFile,0,SEEK_END); //把指针移动到文件的结尾 ,获取文件长度 int len=ftell(pFile); //获取文件长度 pBuf=new char[len+1]; //定义数组长度 rewind(pFile); //把指针移动到文件开头 因为我们一开始把指针移动到结尾,如果不移动回来 会出错 fread(pBuf,1,len,pFile); //读文件 pBuf[len]=0; //把读到的文件最后一位 写为0 要不然系统会一直寻找到0后才结束 MessageBox(pBuf); //显示读到的数据 fclose(pFile); // 关闭文件
C++
fstream提供了三个类,用来实现c++对文件的操作。
ifstream -- 从已有的文件读
ofstream -- 向文件写内容
fstream --打开文件供读写
文件打开模式:
ios::in 读
ios::out 写
ios::app 从文件末尾开始写
ios::binary 二进制模式
ios::nocreate 打开一个文件时,如果文件不存在,不创建文件。
ios::noreplace 打开一个文件时,如果文件不存在,创建该文件
ios::trunc 打开一个文件,然后清空内容
os::ate 打开一个文件时,将位置移动到文件尾
文件指针位置在c++中的用法:
ios::beg 文件头
ios::end 文件尾
ios::cur 当前位置
例子:
file.seekg(0,ios::beg); //让文件指针定位到文件开头
file.seekg(0,ios::end); //让文件指针定位到文件末尾
file.seekg(10,ios::cur); //让文件指针从当前位置向文件末方向移动10个字节
file.seekg(-10,ios::cur); //让文件指针从当前位置向文件开始方向移动10个字节
file.seekg(10,ios::beg); //让文件指针定位到离文件开头10个字节的位置
常用的错误判断方法:
good() 如果文件打开成功
bad() 打开文件时发生错误
eof() 到达文件尾
实例程序:
1. 写入文件
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream in;
in.open("E:\\acm\\in.txt", ios::trunc);
int i;
char a = 'a';
for(i = 1; i <= 26; i ++)
{
if(i < 10)
in<<"0"<<i<<"\t"<<a<<endl;
else
in<<i<<"\t"<<a<<endl;
a ++;
}
in.close();
return 0;
}
2. 读文件
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream op;
op.open("E:\\acm\\in.txt", ios::in);
if(op.fail())
throw runtime_error("Open file error!!!");
char buf[256];
while(!op.eof())
{
op.getline(buf,256,'\n');
cout<<buf<<endl;
}
op.close();
return 0;
}
源自:http://blog.163.com/lichunliang1988116@126/blog/static/26599443201281251054579/