읽기 모드에서 파일을 엽니다. 파일이 있으면 파일의 줄 수를 계산하는 코드를 작성하십시오. 파일이 존재하지 않을 경우 파일이 존재하지 않는다는 오류를 표시합니다.
파일은 기록의 모음(또는) 데이터가 영구적으로 저장되는 하드 디스크의 장소입니다.
다음은 파일에서 수행되는 작업입니다 -
-
파일 이름 지정
-
파일 열기
-
파일에서 읽기
-
파일에 쓰기
-
파일 닫기
구문
다음은 파일을 열고 이름을 지정하는 구문입니다 -
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!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",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!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",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