編寫一個 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP