파일은 기록의 모음이거나 데이터가 영구적으로 저장되는 하드 디스크의 한 장소입니다.
파일 필요
-
프로그램이 종료되면 전체 데이터가 손실됩니다.
-
파일에 저장하면 프로그램이 종료되어도 데이터가 보존됩니다.
-
많은 양의 데이터를 입력할 경우 일반적으로 모두 입력하는 데 시간이 많이 걸립니다.
-
몇 가지 명령을 사용하여 파일 내용에 쉽게 액세스할 수 있습니다.
-
변경 없이 한 컴퓨터에서 다른 컴퓨터로 데이터를 쉽게 이동할 수 있습니다.
-
C 명령을 사용하여 다양한 방법으로 파일에 액세스할 수 있습니다.
파일 작업
C 프로그래밍 언어의 파일에 대한 작업은 다음과 같습니다. -
- 파일 이름 지정
- 파일 열기
- 파일에서 읽기
- 파일에 쓰기
- 파일 닫기
구문
파일 포인터 선언 구문 다음과 같습니다 -
FILE *File pointer;
예:파일 * fptr;
파일 포인터 이름 지정 및 열기 구문 다음과 같습니다 -
File pointer = fopen ("File name", "mode"); 예를 들어, 파일을 여는 모드를 추가하려면 아래에 주어진 구문을 사용하십시오 -
FILE *fp;
fp =fopen ("sample.txt", "a"); 파일이 없으면 새 파일이 생성됩니다.
파일이 존재하면 기존 콘텐츠에 현재 콘텐츠가 추가됩니다.
프로그램
다음은 추가 모드에서 파일을 열고 파일에 있는 줄 수를 계산하는 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");
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 before adding lines are: %d\n",linesCount);
fp=fopen(FILENAME,"a"); //open fine in append mode
while((ch = getchar())!=EOF){
putc(ch,fp);
}
fclose(fp);
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 after adding lines are: %d\n",linesCount);
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -
Total number of lines before adding lines are: 3 WELCOME to Tutorials Its C Programming Language ^Z Total number of after adding lines are: 8