1. 程式人生 > 其它 >C++檔案讀寫操作及加速

C++檔案讀寫操作及加速

01檔案讀寫方法


使用C中的freopen()函式進行開啟檔案並重定向輸入輸出。如下:

#include<iostream>
using namespace std;
int main()
{
    freopen("testfile.txt","w",stdout);

    for(int i=0;i<10;i++)
        cout<<i<<" ";
    return 0;
}

這樣,你就可以使用普通的cin,cout來進行檔案的輸入輸出了,當然你也可以使用printf()等函式。

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    freopen("testfile.txt","w",stdout);

    for(int i=0;i<10;i++)
        printf("%d",i);
    return 0;
}

輸出結果應該為0-9的一行數字。

其中,freopen()的第一個引數為(檔案路徑+)檔名(,即檔案所在的相對路徑或絕對路徑)。第二個引數為描述符:常用的有r(read,讀)、w(write,寫)等。第三個引數為被重定向的流一般有stdin,stdout和stderr。

下面,就來詳解一下這三個引數。

10 freopen()引數的說明


1-char *FileName

第一個引數填檔名。平時做題或者比賽時,因為資料基本上都會和程式放在一塊,所以直接寫檔名即可。程式會讀取同目錄下的對應檔案。

而你如果把資料放在了子資料夾"SubDir"中,那麼就應該使用相對路徑,即相對當前目錄的位置。例如:

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    freopen("SubDir/testfile.txt","w",stdout);

    for(int i=0;i<10;i++)
        printf("%d",i);
    return 0;
}

但是,如果你的資料放在了父級目錄呢?

那就使用絕對路徑。即相對與你碟符(或者說根目錄?)的路徑。

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    freopen("C:\\Users\\Administrator\\Desktop\\testfile.txt","w",stdout);

    for(int i=0;i<10;i++)
        printf("%d",i);
    return 0;
}

注意,Windows平臺下,檔案路徑使用的是反斜槓"\"。而編譯器會理所當然地把你的"\"當成是在轉義——所以,你要轉義你的"\"。也就是使用雙反斜槓"\\"。

2-char *RestrictMode

這個沒什麼好說的,一般只用讀寫足矣。

r(read,讀)、w(write,寫)

3-char *RestrictStream

重定向至的流。

一般使用輸入輸出流,即使用stdin(輸入)、stdout(輸出)。

stderr是標準錯誤輸出裝置流。在預設情況的下,stdout會緩衝——只有當換行的時候,緩衝中的內容才會輸出到你的螢幕。

而stderr則是沒有緩衝的,會直接輸出。在你想讀寫檔案時,請不要用stderr。它會直接輸出到你的螢幕上(輸出錯誤資訊用的)。也就是你程式的執行介面。

當然,這玩意幾乎用不到。

11 檔案讀寫的加速


檔案讀寫加速的方法也很簡單。

1-在一開始關閉同步流加速

使用以下方法:

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    freopen("testfile.txt","w",stdout);
    ios::sync_with_stdio(false);
    for(int i=0;i<100;i++)
        printf("%d",i);
    return 0;
}

加一行碼,即把同步流設定成false。注意,一定要在一開始加!否則你都輸出完了還關啥......

把輸出改為輸出一萬個數(0-9999),看看加了和不加的區別如何:

Process returned 0 (0x0)   execution time : 0.455 s
---------------------------------------------------
Process returned 0 (0x0)   execution time : 0.428 s

上面是沒加的,下面是加了的。

經過多次試驗可以發現,關了同步流比沒關大概要快0.03秒左右。如果資料更大,那麼時間差也會更大。

2-使用"\n"換行

換行時,你可能會使用endl。推薦使用換行符換行——只不過需要注意平臺差異,Windows和Linux的換行符似乎不一樣。

同樣地,我們來對比一下用時:

A組:

#include<iostream>
using namespace std;
int main()
{
    freopen("testfile.txt","w",stdout);
    ios::sync_with_stdio(false);
    for(int i=0;i<10000;i++)
        cout<<i<<endl;
    return 0;
}

B組:

#include<iostream>
using namespace std;
int main()
{
    freopen("testfile.txt","w",stdout);
    ios::sync_with_stdio(false);
    for(int i=0;i<10000;i++)
        cout<<i<<"\n";
    return 0;
}

用時對比:

Process returned 0 (0x0)   execution time : 0.551 s // A組
---------------------------------------------------
Process returned 0 (0x0)   execution time : 0.440 s // B組

可以明顯地看到,使用換行符"\n"會快很多。

(tips:這些加速也是基本的卡常知識哦)