您的位置:首页 > 编程语言 > C语言/C++

\t\t孙鑫 第十二课之一 c/c++文件操作

2012-12-05 17:18 253 查看
1 C语言文件操作
①打开文件
FILE * fopen(const char * path,const char * mode); // 打开文件,mode的取值具体见 附录
eg.
FILE *pFILE = fopen("1.txt", "a+"); //可读可写,追加,文件存在则添加,不存在则创建
②写文件
int fwrite(void *buffer,//要写的缓冲区地址
int size, //要写的这种内容每个单位大小
int count, //要写count个size大小的内容
FILE *fp //文件指针
);
eg.
char *name = "caonimabaidu";
fwrite(name, sizeof(char), strlen(name), pFILE);
name中每个字符的单位大小为sizeof(char), strlen(name)取得从'h'开始直到'\0'位置的字符个数,注意strlen和sizeof的区别
strlen(): 取得从头开始到'\0'的个数,sizeof()取得占的内存大小,即使有内存单位为'\0'也算在内,而strlen遇到'\0'就停止计数。
③读文件
int fread(void *buffer, //读入的buffer
int size, //读入的内容每个单位大小
int count, //读入count个size大小的内容
FILE *fp //文件指针
);
从文件指针位置开始往后读起,因此要注意如果移动了文件指针要复位。
eg.
char ch[100];
memset(ch, 0, sizesof(ch) / sizesof(char));
fread(ch, sizeof(char), sizeof(ch) / sizeof(char), pFILE);

④移动文件指针
int fseek(FILE *stream, //文件指针
long offset,//相对于fromhere的偏移量,单位字节
int fromwhere //某一位置
);
fromhere的取值有三个:SEEK_SET(开始位置), SEEK_CUR(当前位置), SEEK_END(末尾)
eg.
fseek(pFILE, 10L, SEEK_SET); //从开始位置移动10字节位置

⑤取得文件大小
long ftell(FILE *stream);
该函数的功能是取得文件从开始位置到当前文件指针位置的偏移字节数, 因此如果把文件指针移动到末尾时再调用此函数就能取得该文件的总长度
eg.
fseek(pFILE, 0L, SEEK_END); //移动文件指针到文件尾
long len = 0;
len = ftell(pFILE); //取得文件长度
rewind(pFILE): //移动文件指针到开头,因为如果要fread操作的话

⑥Example of reading file

FILE *pFILE = fopen("3.txt", "r");
char *ch = NULL;
fseek(pFILE, 0L, SEEK_END);
int len = 0;
len = ftell(pFILE);
ch = new char[len + 1];
ch[len] = 0; //最后一个置为'\0'
rewind(pFILE); //重要!
fread(ch, sizeof(char), strlen(ch), pFILE);

⑦关于文本文件和二进制文件的区别
以文本文件写入时,当遇到换行符(ASCII==10),转换为回车换行(ASCII == 13, ASCII == 10),在读取文件遇到回车换行时,转换为换行符。
以二进制文件写入时,文件中保存的是数据在内存中的存放形式。
总之,写入和读出时的格式要一致,具体略。

2 C++文件操作
①ASCII文件
ASCII文件的读写用流插入符“<<” 和流提取符“ >>”来实现或者用put, get, getline实现(略)
#include<iostream>
#include<fstream>
int main()
{
int a[10];
ofstream outfile("1.dat", ios::out | ios::noreplace); // 打开输出文件(相对内存),文件不存在则建立
if( !outfile)//如果打开失败
{
cerr<<"打开失败!"<<endl;
exit(1);
}
cout<<"请输入10个数字:"<<endl;
for(int i = 0; i < 10; i ++)
{
cin>>a[i];
outfile>>a[i]>>" "; //输入,以空格区分
}
outfile.close(); //关闭文件

ifstream infile("1.dat", ios::in); //输入文件
int b[5];
for (int j = 0; j < 5; j ++)
{
infile>>b[i]; //输入数组并显示
cout<<b[i]<<" ";
}
infile.close(); //关闭文件
cout<<endl<<endl;

return 0;
}

②二进制文件的读写
对二进制文件的读写是用成员函数write 和 read完成的
istream& read(char *buffer, int len);
ostream& write(const char *buffer, int len); //len单位字节
以二进制形式写文件不用加空格或回车分隔,因为读取的时候是通过字节数区分的,因此不会读错。
eg.
///////输出/////////////////////////
int num[100];
for(int i = 0; i < sizeof(num) / sizeof(int); i ++)
{
num[i] = i;
}
ostream outfile("2.dat", ios::binary | ios::out);
outfile.write((char*)num, sizeof(num)); //注意格式转换

/////////输入///////////////
int number[100];
istream infile("2.dat", ios::binary | ios::in);
infile.read((char*)number, sizeof(number));//注意格式转换

?

?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: