文件是记录的集合,或者是硬盘上的一个位置,数据永久存储在其中。
对文件的操作
C语言编程语言对文件的操作如下−
- 命名文件
- 打开文件
- 从文件中读取
- 写入文件
- 关闭文件
语法
打开文件的语法如下 -
FILE *File pointer;
例如,FILE * fptr;
命名文件的语法如下
File pointer = fopen ("File name", "mode");
例如
fptr = fopen ("sample.txt", "r");
FILE *fp;
fp = fopen ("sample.txt", "w");
文件中的错误处理
文件中的一些错误如下 -
- 尝试读取文件末尾。
- 设备过流。
- 尝试打开无效文件。
- 通过以其他模式打开文件来执行无效操作。
ferror()
它用于在执行读/写操作时检测错误。
ferror()函数的语法如下
语法
int ferror (file pointer);
例如
FILE *fp;
if (ferror (fp))
printf ("error has occurred");
如果成功,则返回零,否则返回非零。
程序
以下是使用 ferror()函数的 C 程序
#include<stdio.h>
int main(){
FILE *fptr;
fptr = fopen("sample.txt","r");
if(ferror(fptr)!=0)
printf("error occurred");
putc('T',fptr);
if(ferror(fptr)!=0)
printf("error occurred");
fclose(fptr);
return 0;
}
输出
当执行上述程序时,它会产生以下结果 -
error occurred
Note: try to write a file in the read mode results an error.
perror()
它用于打印错误。
perror()函数的语法如下
语法
perror (string variable);
例如
FILE *fp;
char str[30] = "Error is";
perror (str);
输出如下 −
Error is: error 0
程序
以下是使用 perror()函数的 C 程序
#include<stdio.h>
int main ( ){
FILE *fp;
char str[30] = "error is";
int i = 20;
fp = fopen ("sample.txt", "r");
if (fp == NULL){
printf ("file doesnot exist");
}
else{
fprintf (fp, "%d", i);
if (ferror (fp)){
perror (str);
printf ("error since file is opened for reading only");
}
}
fclose (fp);
return 0;
}
输出
当执行上述程序时,它会产生以下结果
error is: Bad file descriptor
error since file is opened for reading only
feof()
它用于检查是否已到达(或)未到达文件的末尾。
feof()函数的语法如下
语法
int feof (file pointer);
例如
FILE *fp;
if (feof (fp))
printf ("reached end of the file");
如果成功,则返回非零,否则返回零。
程序
以下是使用 feof()函数的 C 程序
#include<stdio.h>
main ( ){
FILE *fp;
int i,n;
fp = fopen ("number. txt", "w");
for (i=0; i<=100;i= i+10){
putw (i, fp);
}
fclose (fp);
fp = fopen ("number. txt", "r");
printf ("file content is");
for (i=0; i<=100; i++){
n = getw (fp);
if (feof (fp)){
printf ("reached end of file");
break;
}else{
printf ("%d", n);
}
}
fclose (fp);
getch ( );
}
输出
当执行上述程序时,它会产生以下结果
File content is
10 20 30 40 50
60 70 80 90 100
Reached end of the file.
总结
本文详细介绍了C语言中对文件进行操作的基本步骤,包括命名文件、打开文件、读取文件、写入文件以及关闭文件。文中还涵盖了文件操作中的错误处理方法,具体介绍了ferror()
、perror()
和feof()
函数的使用及其示例程序。这些内容为编写健壮的文件操作代码提供了重要的参考,帮助开发者有效处理文件操作中的各种潜在错误。