If you’ve written the C helloworld
program before, you already know basic file I/O in C:
如果您以前编写过C helloworld
程序,那么您已经知道C中的基本文件I / O:
/* A simple hello world in C. */
#include <stdlib.h>
// Import IO functions.
#include <stdio.h>
int main() {
// This printf is where all the file IO magic happens!
// How exciting!
printf("Hello, world!\n");
return EXIT_SUCCESS;
}
File handling is one of the most important parts of programming. In C, we use a structure pointer of a file type to declare a file:
文件处理是编程中最重要的部分之一。 在C语言中,我们使用文件类型的结构指针来声明文件:
FILE *fp;
C provides a number of build-in function to perform basic file operations:
C提供了许多内置函数来执行基本文件操作:
fopen()
- create a new file or open a existing filefopen()
-创建一个新文件或打开一个现有文件fclose()
- close a filefclose()
-关闭文件getc()
- reads a character from a filegetc()
-从文件中读取字符putc()
- writes a character to a fileputc()
-将字符写入文件fscanf()
- reads a set of data from a filefscanf()
-从文件中读取一组数据fprintf()
- writes a set of data to a filefprintf()
-将一组数据写入文件getw()
- reads a integer from a filegetw()
-从文件读取整数putw()
- writes a integer to a fileputw()
-将整数写入文件fseek()
- set the position to desire pointfseek()
-将位置设置为期望点ftell()
- gives current position in the fileftell()
-给出文件中的当前位置rewind()
- set the position to the beginning pointrewind()
-将位置设置为起点
开启档案 (Opening a file)
The fopen()
function is used to create a file or open an existing file:
fopen()
函数用于创建文件或打开现有文件:
fp = fopen(const char filename,const char mode);
There are many modes for opening a file:
有多种打开文件的模式:
r
- open a file in read moder
以读取模式打开文件w
- opens or create a text file in write modew
在写入模式下打开或创建文本文件a
- opens a file in append modea
-打开追加模式文件r+
- opens a file in both read and write moder+
-以读写模式打开文件a+
- opens a file in both read and write modea+
-以读写模式打开文件w+
- opens a file in both read and write modew+
-以读写模式打开文件
Here’s an example of reading data from a file and writing to it:
这是从文件读取数据并将其写入的示例:
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("hello.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("hello.txt", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
fclose(fp);
}
Now you might be thinking, "This just prints text to the screen. How is this file IO?”
现在您可能在想:“这只是将文本打印到屏幕上。此文件的IO如何?”
The answer isn’t obvious at first, and needs some understanding about the UNIX system. In a UNIX system, everything is treated as a file, meaning you can read from and write to it.
答案一开始并不明显,并且需要对UNIX系统有所了解。 在UNIX系统中,所有内容都被视为文件,这意味着您可以对其进行读取和写入。
This means that your printer can be abstracted as a file since all you do with a printer is write with it. It is also useful to think of these files as streams, since as you’ll see later, you can redirect them with the shell.
这意味着您的打印机可以抽象为文件,因为您对打印机所做的全部工作都是用它来写的。 将这些文件视为流也很有用,因为稍后将看到,您可以使用shell重定向它们。
So how does this relate to helloworld
and file IO?
那么,这与helloworld
和文件IO有何关系?
When you call printf
, you are really just writing to a special file called stdout
, short for standard output. stdout
represents the standard output as decided by your shell, which is usually the terminal. This explains why it printed to your screen.
当您调用printf
,您实际上只是在写一个名为stdout
的特殊文件,它是标准输出的缩写。 stdout
表示由外壳决定的标准输出,通常是终端。 这解释了为什么将其打印到屏幕上。
There are two other streams (i.e. files) that are available to you with effort, stdin
and stderr
. stdin
represents the standard input, which your shell usually attaches to the keyboard. stderr
represents the standard error output, which your shell usually attaches to the terminal.
还有另外两个流(即文件)可供您使用: stdin
和stderr
。 stdin
表示标准输入 ,您的外壳通常将其附加到键盘。 stderr
代表标准错误输出,您的外壳通常将其附加到终端。
基本文件IO,或我如何学习铺设管道 (Rudimentary File IO, or How I Learned to Lay Pipes)
Enough theory, let’s get down to business by writing some code! The easiest way to write to a file is to redirect the output stream using the output redirect tool, >
.
有足够的理论,让我们开始编写一些代码! 写入文件的最简单方法是使用输出重定向工具>
重定向输出流。
If you want to append, you can use >>
:
如果要附加,可以使用>>
:
# This will output to the screen...
./helloworld
# ...but this will write to a file!
./helloworld > hello.txt
The contents of hello.txt
will, not surprisingly, be
毫不奇怪, hello.txt
的内容将是
Hello, world!
Say we have another program called greet
, similar to helloworld
, that greets you with a given name
:
假设我们还有另一个名为greet
程序,类似于helloworld
,它使用一个给定的name
来问候您:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Initialize an array to hold the name.
char name[20];
// Read a string and save it to name.
scanf("%s", name);
// Print the greeting.
printf("Hello, %s!", name);
return EXIT_SUCCESS;
}
Instead of reading from the keyboard, we can redirect stdin
to read from a file using the <
tool:
除了使用键盘进行读取外,我们还可以使用<
工具将stdin
重定向为从文件读取:
# Write a file containing a name.
echo Kamala > name.txt
# This will read the name from the file and print out the greeting to the screen.
./greet < name.txt
# ==> Hello, Kamala!
# If you wanted to also write the greeting to a file, you could do so using ">".
Note: these redirection operators are in bash
and similar shells.
注意:这些重定向操作符在bash
和类似的shell中。
真正的交易 (The Real Deal)
The above methods only worked for the most basic of cases. If you wanted to do bigger and better things, you will probably want to work with files from within C instead of through the shell.
以上方法仅适用于最基本的情况。 如果您想做更大更好的事情,您可能希望使用C内部而不是通过Shell处理文件。
To accomplish this, you will use a function called fopen
. This function takes two string parameters, the first being the file name and the second being the mode.
为此,您将使用一个名为fopen
的函数。 此函数采用两个字符串参数,第一个是文件名,第二个是模式。
The mode are basically permissions, so r
for read, w
for write, a
for append. You can also combine them, so rw
would mean you could read and write to the file. There are more modes, but these are the most commonly used.
该模式基本上是权限,因此r
表示读取, w
表示写入, a
表示追加。 您也可以将它们组合在一起,所以rw
表示您可以读写文件。 模式更多,但是这些是最常用的模式。
After you have a FILE
pointer, you can use basically the same IO commands you would’ve used, except that you have to prefix them with f
and the first argument will be the file pointer. For example, printf
’s file version is fprintf
.
有了FILE
指针后,就可以使用与IO基本上相同的IO命令,除了必须给它们加上f
前缀并且第一个参数是文件指针。 例如, printf
的文件版本为fprintf
。
Here’s a program called greetings
that reads a from a file containing a list of names and write the greetings to another file:
这是一个名为greetings
的程序,该程序从包含名称列表的文件中读取一个并将问候语写入另一个文件:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Create file pointers.
FILE *names = fopen("names.txt", "r");
FILE *greet = fopen("greet.txt", "w");
// Check that everything is OK.
if (!names || !greet) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
// Greetings time!
char name[20];
// Basically keep on reading untill there's nothing left.
while (fscanf(names, "%s\n", name) > 0) {
fprintf(greet, "Hello, %s!\n", name);
}
// When reached the end, print a message to the terminal to inform the user.
if (feof(names)) {
printf("Greetings are done!\n");
}
return EXIT_SUCCESS;
}
Suppose names.txt
contains the following:
假设names.txt
包含以下内容:
Kamala
Logan
Carol
Then after running greetings
the file greet.txt
will contain:
然后,在运行greetings
,文件greet.txt
将包含:
Hello, Kamala!
Hello, Logan!
Hello, Carol!
翻译自: https://www.freecodecamp.org/news/file-handling-in-c-how-to-open-close-and-write-to-files/