如何在未知的文件中讀取數據
如果是完全未知的話可以用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 |
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函數,而文件流是相當慢的(相對而言)。
由於最近比較忙,過段時間再做一個性能測試。