Computer Programming 简明教程
Computer Programming - File I/O
Computer Files
计算机文件用于以纯文本、图像数据或任何其他内容之类的数字格式存储数据。可以将计算机文件组织在不同的目录中。文件用于保存数字数据,而目录用于保存文件。
A computer file is used to store data in digital format like plain text, image data, or any other content. Computer files can be organized inside different directories. Files are used to keep digital data, whereas directories are used to keep files.
计算机文件可以被视为纸质文件的数字对应物。在编程时,在带有不同扩展名的文本文件中保存源代码,例如,C 编程文件以 .c 扩展名结尾,Java 编程文件以 .java 结尾,Python 文件以 .py 结尾。
Computer files can be considered as the digital counterpart of paper documents. While programming, you keep your source code in text files with different extensions, for example, C programming files end with the extension .c, Java programming files with .java, and Python files with .py.
File Input/Output
通常,使用文本编辑器(如记事本、MS Word、MS Excel 或 MS Powerpoint 等)创建文件。但是,许多时候,我们也需要使用计算机程序创建文件。我们可以使用计算机程序修改现有文件。
Usually, you create files using text editors such as notepad, MS Word, MS Excel or MS Powerpoint, etc. However, many times, we need to create files using computer programs as well. We can modify an existing file using a computer program.
文件输入表示写入文件的数据,文件输出表示从文件中读取的数据。实际上,输入和输出项更与屏幕输入和输出相关。当我们在屏幕上显示结果时,称为输出。同样,如果我们从命令提示符向程序提供一些输入,则称为输入。
File input means data that is written into a file and file output means data that is read from a file. Actually, input and output terms are more related to screen input and output. When we display a result on the screen, it is called output. Similarly, if we provide some input to our program from the command prompt, then it is called input.
现在,记住这一点就足够了:写入文件是文件输入,从文件中读取内容是文件输出。
For now, it is enough to remember that writing into a file is file input and reading something from a file is file output.
File Operation Modes
在我们开始使用计算机程序处理任何文件之前,我们需要创建一个新文件(如果它不存在)或打开一个已存在的文件。在这两种情况下,我们都可以在以下模式下打开文件 −
Before we start working with any file using a computer program, either we need to create a new file if it does not exist or open an already existing file. In either case, we can open a file in the following modes −
-
Read-Only Mode − If you are going to just read an existing file and you do not want to write any further content in the file, then you will open the file in read-only mode. Almost all the programming languages provide syntax to open files in read-only mode.
-
Write-Only Mode − If you are going to write into either an existing file or a newly created file but you do not want to read any written content from that file, then you will open the file in write-only mode. All the programming languages provide syntax to open files in write-only mode.
-
Read & Write Mode − If you are going to read as well as write into the same file, then you will open file in read & write mode.
-
Append Mode − When you open a file for writing, it allows you to start writing from the beginning of the file; however it will overwrite existing content, if any. Suppose we don’t want to overwrite any existing content, then we open the file in append mode. Append mode is ultimately a write mode, which allows content to be appended at the end of the file. Almost all the programming languages provide syntax to open files in append mode.
在随后的章节中,我们将了解如何打开一个新文件、如何写入该文件以及如何在同一文件中读取和追加更多内容。
In the following sections, we will learn how to open a fresh new file, how to write into it, and later, how to read and append more content into the same file.
Opening Files
你可以使用 fopen() 函数创建新文件或打开现有文件。此调用将初始化一个 FILE 类型的对象,该对象包含控制流所需的所有信息。以下是该函数调用的原型,即签名 −
You can use the fopen() function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Here is the prototype, i.e., signature of this function call −
FILE *fopen( const char * filename, const char * mode );
在此, filename 是字符串字面量,将使用它来命名文件和访问 mode 可以具有以下值之一 −
Here, filename is string literal, which you will use to name your file and access mode can have one of the following values −
Sr.No |
Mode & Description |
1 |
r Opens an existing text file for reading purpose. |
2 |
w Opens a text file for writing. If it does not exist, then a new file is created. Here, your program will start writing content from the beginning of the file. |
3 |
a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here, your program will start appending content in the existing file content. |
4 |
r+ Opens a text file for reading and writing both. |
5 |
w+ Opens a text file for both reading and writing. It first truncates the file to zero length, if it exists; otherwise creates the file if it does not exist. |
6 |
a+ Opens a text file for both reading and writing. It creates a file, if it does not exist. The reading will start from the beginning, but writing can only be appended. |
Closing a File
要关闭文件,请使用 fclose( ) 函数。此函数的原型为 −
To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
fclose( ) 函数在成功时返回零,或在关闭文件时出错时返回 EOF 特殊字符。此函数实际上会将缓冲区中仍处于未决状态的任何数据写入至文件,关闭文件并释放用于该文件的所有内存。EOF 是在头文件 stdio.h 中定义的常数。
The fclose( ) function returns zero on success, or EOF, special character, if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
C 标准库提供了用于逐个字符或以固定长度字符串形式读写文件的各种函数。我们将在下一节中了解其中的一些函数。
There are various functions provided by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see a few of them in the next section.
Writing a File
下面列出用于将单个字符写入流的最简单的函数 −
Given below is the simplest function to write individual characters to a stream −
int fputc( int c, FILE *fp );
函数 fputc() 将参数 c 的字符值写入由 fp 引用的输出流。它会在成功时返回已写入的字符,否则如果出错,则返回 EOF 。您可以使用以下函数将以 null 结尾的字符串写入流 −
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success, otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );
函数 fputs() 将字符串 s 写入由 fp 引用的文件中。它在成功时返回一个非负值,否则在出现任何错误的情况下返回 EOF 。您还可以使用函数 int fprintf(FILE *fp,const char *format, …) 将字符串写入文件中。请尝试以下示例 −
The function fputs() writes the string s into the file referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can also use the function int fprintf(FILE *fp,const char *format, …) to write a string into a file. Try the following example −
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
编译并执行以上代码时,它将在 /tmp 目录中创建一个新文件 test.txt ,并使用两个不同的函数写入两行。让我们在下一节中读取此文件。
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.
Reading a File
下面列出用于逐个字符读取文本文件的最简单的函数 −
Given below is the simplest function to read a text file character by character −
int fgetc( FILE * fp );
fgetc() 函数从由 fp 引用的输入文件中读取字符。返回值是所读取的字符;或在出现任何错误的情况下,它会返回 EOF 。以下函数允许您从流中读取字符串 −
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read; or in case of any error, it returns EOF. The following function allows you to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );
函数 fgets() 从由 fp 引用的输入流中最多读取 n - 1 个字符。它将读取的字符串复制到缓冲区 buf 中,并追加一个 null 字符来终止该字符串。
The function fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
如果此函数在读取到最大字符数量之前遇到换行符 '\n' 或 EOF,那么它只会返回已读取到的字符(包括换行符)。您还可以使用 int fscanf(FILE *fp, const char *format, …) 从文件中读取字符串,但它会在遇到第一个空格字符后停止读取。
If this function encounters a newline character '\n' or EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, …) to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);
}
编译并执行以上代码时,它将读取上一节中创建的文件,并生成以下结果 −
When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
1 : This
2 : is testing for fprintf...
3 : This is testing for fputs...
让我们分析一下这里发生了什么。首先, fscanf() 方法读取 This ,因为之后它遇到了一个空格。第二个调用是 fgets() ,它读取到遇到行尾为止的剩余行。最后,最后一个调用 fgets() 完全读到了第二行。
Let’s analyze what happened here. First, the fscanf() method reads This because after that, it encountered a space. The second call is for fgets(), which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.
File I/O in Java
Java 提供了更丰富的函数集来处理文件 I/O。有关此主题的更多信息,我们建议您查看我们的 Java 教程。
Java provides even richer set of functions to handle File I/O. For more on this topic, we suggest you to check our Java Tutorials.
在这里,我们将看到一个简单的 Java 程序,它等同于上面介绍的 C 程序。此程序将打开一个文本文件,向其中写入几行文本,并关闭该文件。最后,打开相同的文件,然后从已创建的文件中读取。您可以尝试执行以下程序以查看输出 −
Here, we will see a simple Java program, which is equivalent to the C program explained above. This program will open a text file, write a few text lines into it, and close the file. Finally, the same file is opened and then read from an already created file. You can try to execute the following program to see the output −
import java.io.*;
public class DemoJava {
public static void main(String []args) throws IOException {
File file = new File("/tmp/java.txt");
// Create a File
file.createNewFile();
// Creates a FileWriter Object using file object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This is testing for Java write...\n");
writer.write("This is second line...\n");
// Flush the memory and close the file
writer.flush();
writer.close();
// Creates a FileReader Object
FileReader reader = new FileReader(file);
char [] a = new char[100];
// Read file content in the array
reader.read(a);
System.out.println( a );
// Close the file
reader.close();
}
}
当执行上述程序时,它将生成以下结果 −
When the above program is executed, it produces the following result −
This is testing for Java write...
This is second line...
File I/O in Python
以下程序展示了相同的打开新文件、向其中写入一些内容的功能,最后,读取相同的文件 −
The following program shows the same functionality to open a new file, write some content into it, and finally, read the same file −
# Create a new file
fo = open("/tmp/python.txt", "w")
# Writes the content to the file
fo.write( "This is testing for Python write...\n");
fo.write( "This is second line...\n");
# Close the file
fo.close()
# Open existing file
fo = open("/tmp/python.txt", "r")
# Read file content in a variable
str = fo.read(100);
print str
# Close opened file
fo.close()
执行上述代码后,将生成以下结果 −
When the above code is executed, it produces the following result −
This is testing for Python write...
This is second line...