【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 string | Meaning | Explanation | Action if file already exists | Action if file does not exist |
---|---|---|---|---|
“r” | read | Open a file for reading | read from start | failure to open |
“w” | write | Create a file for writing | destroy contents | create new |
“a” | append | Append to a file | write to end | create new |
“r+” | read extended | Open a file for read/write | read from start | error |
“w+” | write extended | Create a file for read/write | destroy contents | create new |
“a+” | append extended | Open a file for read/write | write to end | create new |
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 ↩
相关文章推荐
- C++ 读写操作同一个文件的几种方法
- java中,对文件进行追加内容操作的三种方法!
- C++(不需要MFC库,不需要第三方库)对文件进行操作的几种方法
- java读取文件内容的三种方法代码片断分享(java文件操作)
- 操作sys/device下文件节点的三种方法
- seo复习,建立.htaccess文件的三种方法
- 三种方法实现php网络请求(表单操作文件上传)
- php读取操作大文件,超出内存大小,三种方法
- 【C++】实现双向链表的所有操作,包括逆置双链表(三种方法)
- c++关于文件夹(文件)的相关操作_findfirst,_findnext和_findclose方法
- C++文件(流操作)(方式方法)
- 【C++】实现双向链表的所有操作,包括逆置双链表(三种方法)
- java中,对文件进行追加内容操作的三种方法
- 操作 Wave 文件(7): 建立一个空的 Wave 文件(三种方法)
- 谈vb目录文件操作的三种方法
- C/C++文件操作fopen/fscanf/ fprintf/ fclose简单使用方法
- 在Delphi中使用CreateOleObject方法对WORD文件进行操作
- 在C++中实现文件的读写的基本方法
- ASP.NET中的文件操作常用方法
- .NET框架下编程操作XML文档的三种方法