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

C++常用的读写文件代码

2014-07-26 22:45 676 查看
一.首先常用的C读写文件方法函数,C++中完美兼容使用C代码,只是头文件略有不同。以下是C++代码:

1.写文件字符串

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;

int main()
{
    FILE *fp;                     //文件指针
    char buf[10240]="hello , everyone!!!";             //写入的字符串
    if((fp = fopen("C:\\file1.txt","w+"))==NULL){  //打开文件,若文件不存在则创建文件
        printf("can not open file");
        exit(0);
    }

    //一次性写入
    fwrite(buf,sizeof(char),strlen(buf),fp);
    fclose(fp);

    return 0;
}

2.读文件字符串

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;

int main()
{
    FILE *fd;                     //文件指针
    char buf[10240];             //读入的字符串保存区
    if((fd = fopen("C:\\file.txt","r+"))==NULL){  //打开文件
        printf("can not open file");
        exit(0);
    }

    //得到文件内容的长度
    fseek(fd,0,SEEK_END); //把文件的位置指针移到文件尾
    long len=ftell(fd); //获取文件长度;
    fseek(fd,0,SEEK_SET); //文件指针返回头部

    fread(buf,sizeof(char),len,fd); //读文件
    fclose(fd);

    return 0;
}
char数组buf保存需要写入文件的字符串,文件指针保存文件中读写的位置;

fopen函数有两个参数,函数原型FILE * fopen(const
char * path,const char * mode);

第一个参数path为文件的路径,第二个参数为文件的读写模式,常用的有w,r;

w表示写,r表示读,在后面加上加号就是读写皆可,即w+和r+一样,都表示文件读写,但是具体含义有区别,详见下文;

若想二进制读取,则在后面加b,如wb+,rb+;

在非二进制读取时,windows下回将0a转换成odoa,即\n转换成\r\n;

若想追加方式读写,则为a+或者ab+;

fopen函数中w+和r+以及a+的区别:

r+从文件头开始写,保留文件中没有被覆盖的那部分内容,文件必须存在;

w+写文件时,文件不存在会先创建文件,支多级目录创建,若文件存在,会清空文件,从头开始写文件;

a+是支持追加写文件,文件不存在也会跟 w+一样支持创建,若文件存在,会找到文件尾追加写入;

二.C++字符串流的文件读写

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream in("C:\\file.txt",ifstream::in);   //第二个参数可省
    ofstream out("C:\\file.txt",ofstream::out);     //第二个参数可省
 // ofstream out("C:\\file.txt",ofstream::app);    //追加写文件
    char buf[10240]="hello everyone!!!!";
    if(in)
        in>>buf;          //读文件
    else
        printf("can not open the file");

    if(out)
        out<<buf;         //写文件
    else
        printf("can not open the file");

    return 0;
}


头文件ftream定义了三个类型来支持文件IO, ifstream ofstream fstream;

可以用IO运算符(<<和>>)来读写文件,也可以用getline从ifstream 中读取数据;

默认构造函数的第二个参数为文件模式(file mode),如下:

文件模式

in以读方式打开
out 以写方式打开
app每次写操作前均定位到文件末尾
ate打开文件后定位到文件末尾
trunc截断文件
binary以二进制方式进行IO
可以使用open函数代替默认构造函数,形如:

ifstream in;
in.open("C:\\file.txt",ifstream::in);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: