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

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

2016-10-05 09:17 260 查看

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

如果是完全未知的话可以用
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函数,而文件流是相当慢的(相对而言)。

由于最近比较忙,过段时间再做一个性能测试。
http://en.cppreference.com/w/c/io/freopen
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp 文件