编写一个 C 程序来查找现有文件中的行总数
以读取模式打开文件。如果文件存在,编写代码以计算文件中行数。如果文件不存在,显示文件不存在错误。
文件是集合记录(或)它是硬盘上的数据永久存储的地方。
文件执行的操作如下
文件命名
打开文件
读取文件
写入文件
关闭文件
语法
打开和命名文件的语法如下
1) FILE *File pointer; Eg : FILE * fptr; 2) File pointer = fopen ("File name", "mode"); Eg : fptr = fopen ("sample.txt", "r"); FILE *fp; fp = fopen ("sample.txt", "w");
程序 1
#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"); 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 Note: employee details.txt file consist of Pinky 20 5000.000000 Here total number of line are 3
程序 2
在这个程序中,我们将演示如何在文件中找到文件夹中没有的总行数。
#include <stdio.h> #define FILENAME "sample.txt" int main(){ FILE *fp; char ch; int linesCount=0; //open file in write mode fp=fopen(FILENAME,"w"); printf ("enter text press ctrl+z of the end"); while ((ch = getchar( ))!=EOF){ fputc(ch, fp); } fclose(fp); //open file in read more fp=fopen(FILENAME,"r"); 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; }
输出
enter text press ctrl+z of the end Hi welcome to Tutorials Point C Pogramming Question & answers ^Z Total number of lines are: 2
广告