【C++复习向】三种操作文件的方法

如何在未知的文件中读取数据

如果是完全未知的话可以用getchar 等读取字符串的函数直接将数据由字符串形式保存后再进行转化。
如果是已知数据类型但未知数据长度可以用while(scanf("%d",&x)==1)或while(scanf("%d".&x)!=EOF) 这里的scanf()函数在成功对内存进行读写时会返回一个int型(应该是),大小为成功写入数据的个数。而EOF(end of file)则是文件结尾的一个特殊的字符。

用重定向读取文件

其实就是用freopen 函数来读取,该函数位于stdio.h中,C++下用cstdio
范例:

#include<cstdio>

freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);

int main(void)
{
    int x;
    scanf("%d",&x);
    printf("%d",x);
    return 0;
}

FILE *freopen( const char *restrict filename, const char *restrict mode,
FILE *restrict stream );
freopen的第一个参数是字符串形式的文件名,第二个是字符串形式的mode参数,第三个是文件形式的流名称。

File access mode stringMeaningExplanationAction if file already existsAction if file does not exist
“r”readOpen a file for readingread from startfailure to open
“w”writeCreate a file for writingdestroy contentscreate new
“a”appendAppend to a filewrite to endcreate new
“r+”read extendedOpen a file for read/writeread from starterror
“w+”write extendedCreate a file for read/writedestroy contentscreate new
“a+”append extendedOpen a file for read/writewrite to endcreate new

File access mode flag “b” can optionally be specified to open a file in binary mode. This flag has effect only on Windows systems.
On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator.

File access mode flag “x” can optionally be appended to “w” or “w+” specifiers. This flag forces the function to fail if the file exists, instead of overwriting it.
1

//可以用ifdef来切换输入输出
#define LOCAL
#ifdef LOCAL
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif

这样要切换文件输入输出时只要将#define LOCAL给注释掉就可以了

fin与fout函数

fin,fout函数同样定义于标准输入输出库(stdio.h)中,使用范例

#include<cstdio>
int main(void)
{
    FILE *fin,*fout;
    fin=fopen("in.txt","rb");
    fout=fopen("out.txt","wb");
    int x;
    fscanf(fin,"%d",&x);
    fprintf(fout,"%d",x);
    fclose(fin);
    fclose(fout);
    return 0;
}

fopen的第二个参数与freopen相同

文件流fstream

#include<fstream>
using namespace std;
ifstream fin("in.txt");
ofstream fout("out.txt");
int main(void)
{
    int a,b;
    fin>>a>>b;
    fout<<a+b<<"\n";
    return 0;
}

速度对比

嗯,按我的老师的说法,速度上标准输入输出>I/O流输入输出>sstream、fstream输入输出
也就是说,上面方法上重定向的速度基本是最快的(重定向后使用标准输入输出),然后是fin、fout函数,而文件流是相当慢的(相对而言)。
由于最近比较忙,过段时间再做一个性能测试。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值