檔案I/O操作
我們需要檔案來儲存程式終止時的程式輸出。使用檔案,我們可以使用不同語言中的各種命令訪問相關資訊。
以下是一些可以對檔案執行的操作列表:
- 建立新檔案
- 開啟現有檔案
- 讀取檔案內容
- 搜尋檔案中的資料
- 寫入新檔案
- 更新現有檔案的內容
- 刪除檔案
- 關閉檔案
寫入檔案
要將內容寫入檔案,我們首先需要開啟所需檔案。如果指定的檔案不存在,則會建立一個新檔案。
讓我們看看如何使用C++將內容寫入檔案。
示例
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("Tempfile.txt", ios::out);
myfile << "Writing Contents to file.\n";
cout << "Data inserted into file";
myfile.close();
return 0;
}
注意:
fstream是用於控制檔案讀/寫操作的流類。
ofstream是用於將內容寫入檔案的流類。
讓我們看看如何使用Erlang(一種函數語言程式設計語言)將內容寫入檔案。
-module(helloworld).
-export([start/0]).
start() ->
{ok, File1} = file:open("Tempfile.txt", [write]),
file:write(File1,"Writting contents to file"),
io:fwrite("Data inserted into file\n").
注意:
要開啟檔案,我們必須使用open(filename,mode)。
寫入檔案內容的語法:write(filemode,file_content)。
輸出:執行此程式碼時,“Writing contents to file”將寫入檔案Tempfile.txt中。如果檔案有任何現有內容,則現有內容將被覆蓋。
從檔案讀取
要從檔案讀取,我們首先必須以讀取模式開啟指定的檔案。如果檔案不存在,則其相應方法返回NULL。
以下程式演示瞭如何在C++中讀取檔案內容:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string readfile;
ifstream myfile ("Tempfile.txt",ios::in);
if (myfile.is_open()) {
while ( getline (myfile,readfile) ) {
cout << readfile << '\n';
}
myfile.close();
} else
cout << "file doesn't exist";
return 0;
}
它將產生以下輸出:
Writing contents to file
注意:在這個程式中,我們使用“ios::in”以讀取模式開啟文字檔案,然後將其內容列印到螢幕上。我們使用了while迴圈,使用“getline”方法逐行讀取檔案內容。
以下程式演示瞭如何使用Erlang執行相同的操作。在這裡,我們將使用read_file(filename)方法讀取指定檔案中的所有內容。
-module(helloworld).
-export([start/0]).
start() ->
rdfile = file:read_file("Tempfile.txt"),
io:fwrite("~p~n",[rdfile]).
它將產生以下輸出:
ok, Writing contents to file
刪除現有檔案
我們可以使用檔案操作刪除現有檔案。以下程式演示瞭如何使用C++刪除現有檔案:
#include <stdio.h>
int main () {
if(remove( "Tempfile.txt" ) != 0 )
perror( "File doesn’t exist, can’t delete" );
else
puts( "file deleted successfully " );
return 0;
}
它將產生以下輸出:
file deleted successfully
以下程式演示瞭如何在Erlang中執行相同的操作。在這裡,我們將使用delete(filename)方法刪除現有檔案。
-module(helloworld).
-export([start/0]).
start() ->
file:delete("Tempfile.txt").
輸出:如果檔案“Tempfile.txt”存在,則它將被刪除。
確定檔案大小
以下程式演示瞭如何使用C++確定檔案大小。這裡,函式fseek將與流關聯的位置指示器設定為新的位置,而ftell返回流中的當前位置。
#include <stdio.h>
int main () {
FILE * checkfile;
long size;
checkfile = fopen ("Tempfile.txt","rb");
if (checkfile == NULL)
perror ("file can’t open");
else {
fseek (checkfile, 0, SEEK_END); // non-portable
size = ftell (checkfile);
fclose (checkfile);
printf ("Size of Tempfile.txt: %ld bytes.\n",size);
}
return 0;
}
輸出:如果檔案“Tempfile.txt”存在,則它將顯示其大小(以位元組為單位)。
以下程式演示瞭如何在Erlang中執行相同的操作。在這裡,我們將使用file_size(filename)方法確定檔案的大小。
-module(helloworld).
-export([start/0]).
start() ->
io:fwrite("~w~n",[filelib:file_size("Tempfile.txt")]).
輸出:如果檔案“Tempfile.txt”存在,則它將顯示其大小(以位元組為單位)。否則,它將顯示“0”。