文件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”。