解释C语言中文件的读取模式操作
文件是记录的集合,或者说是硬盘上用于永久存储数据的地方。
文件的作用
程序终止时,所有数据都会丢失。
将数据存储在文件中,即使程序终止,数据仍然保留。
如果您想输入大量数据,通常需要花费大量时间才能全部输入。
我们可以使用少量命令轻松访问文件的内容。
您可以轻松地在计算机之间移动数据,而无需更改。
通过使用C命令,我们可以以不同的方式访问文件。
文件操作
C编程语言中的文件操作如下:
- 命名文件
- 打开文件
- 从文件中读取
- 写入文件
- 关闭文件
语法
**声明文件指针**的语法如下:
FILE *File pointer;
例如,FILE * fptr;
**命名和打开文件指针**的语法如下:
File pointer = fopen ("File name", "mode");例如,要以读取模式打开文件,请使用以下语法:
FILE *fp
fp =fopen ("sample.txt", "r");如果文件不存在,则fopen函数返回NULL值。
如果文件存在,则成功从文件读取数据。
示例
以下是打开文件以进行读取并计算文件中存在的行数的C程序:
#include<stdio.h>
#define FILENAME "Employee Details.txt"
int main(){
FILE *fp;
char ch;
int linesCount=0;
//open file in read more
fp=fopen(FILENAME,"r"); // already existing need to be open in read mode
if(fp==NULL){
printf("File \"%s\" does not exist!!!
",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='
')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d
",linesCount);
return 0;
}输出
执行上述程序时,会产生以下结果:
Total number of lines are: 3
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP