编写一个 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");
方案一
#include输出结果#define FILENAME "Employee Details.txt" int main(){ FILE *fp; char ch; int linesCount=0; //在阅读更多中打开文件 fp=fopen(FILENAME,"r"); if(fp==NULL){ printf("File \"%s\" does not exist!!!\n",FILENAME); return -1; } //逐个字符读取并检查新行 while((ch=getc(fp))!=EOF){ if(ch=='\n') linesCount++; } //关闭文件 fclose(fp); //打印行数 printf("Total number of lines are: %d\n",linesCount); return 0; }
Total number of lines are: 3 Note: employeedetails.txtfile consist of Pinky 20 5000.000000 Here total number of line are 3
方案二
在这个程序中,我们将看到如何在文件夹中不存在的文件中查找总行数。
#include输出结果#define FILENAME "sample.txt" int main(){ FILE *fp; char ch; int linesCount=0; //以写模式打开文件 fp=fopen(FILENAME,"w"); printf ("enter text press ctrl+z of the end"); while ((ch = getchar( ))!=EOF){ fputc(ch, fp); } fclose(fp); //在阅读更多中打开文件 fp=fopen(FILENAME,"r"); if(fp==NULL){ printf("File \"%s\" does not exist!!!\n",FILENAME); return -1; } //逐个字符读取并检查新行 while((ch=getc(fp))!=EOF){ if(ch=='\n') linesCount++; } //关闭文件 fclose(fp); //打印行数 printf("Total number of lines are: %d\n",linesCount); return 0; }
enter text press ctrl+z of the end Hi welcome to nhooo.com C Pogramming Question & answers ^Z Total number of lines are: 2