📅  最后修改于: 2020-10-22 08:25:41             🧑  作者: Mango
在编程中,我们可能需要多次生成某些特定的输入数据。有时仅在控制台上显示数据是不够的。要显示的数据可能非常大,并且只能在控制台上显示有限数量的数据,并且由于内存易失,因此不可能一次又一次地恢复以编程方式生成的数据。但是,如果需要这样做,我们可以将其存储在易失性的本地文件系统中,并且每次都可以访问。在这里,需要使用C处理文件。
C中的文件处理使我们能够通过C程序创建,更新,读取和删除存储在本地文件系统中的文件。可以对文件执行以下操作。
C库中有许多函数可以打开,读取,写入,搜索和关闭文件。文件功能列表如下:
No. | Function | Description |
---|---|---|
1 | fopen() | opens new or existing file |
2 | fprintf() | write data into the file |
3 | fscanf() | reads data from the file |
4 | fputc() | writes a character into the file |
5 | fgetc() | reads a character from file |
6 | fclose() | closes the file |
7 | fseek() | sets the file pointer to given position |
8 | fputw() | writes an integer to file |
9 | fgetw() | reads an integer from file |
10 | ftell() | returns current position |
11 | rewind() | sets the file pointer to the beginning of the file |
我们必须先打开文件,然后才能对其进行读取,写入或更新。 fopen()函数用于打开文件。下面给出了fopen()的语法。
FILE *fopen( const char * filename, const char * mode );
fopen()函数接受两个参数:
我们可以在fopen()函数使用以下模式之一。
Mode | Description |
---|---|
r | opens a text file in read mode |
w | opens a text file in write mode |
a | opens a text file in append mode |
r+ | opens a text file in read and write mode |
w+ | opens a text file in read and write mode |
a+ | opens a text file in read and write mode |
rb | opens a binary file in read mode |
wb | opens a binary file in write mode |
ab | opens a binary file in append mode |
rb+ | opens a binary file in read and write mode |
wb+ | opens a binary file in read and write mode |
ab+ | opens a binary file in read and write mode |
fopen函数以以下方式工作。
考虑以下示例,该示例以写模式打开文件。
#include
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
文件的内容将被打印。
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
fclose()函数用于关闭文件。对文件执行所有操作后,必须将其关闭。 fclose()函数的语法如下:
int fclose( FILE *fp );