파일은 기록의 모음(또는) 데이터가 영구적으로 저장되는 하드 디스크의 한 장소입니다. C 명령을 사용하여 다양한 방식으로 파일에 액세스합니다.
C 언어로 된 파일 필요
-
프로그램이 종료되면 전체 데이터가 손실되며 파일에 저장하면 프로그램이 종료되더라도 데이터가 보존됩니다.
-
일반적으로 많은 양의 데이터를 입력할 경우 모두 입력하는 데 시간이 많이 걸립니다.
-
모든 데이터가 포함된 파일이 있는 경우 C에서 몇 가지 명령을 사용하여 파일 내용에 쉽게 액세스할 수 있습니다.
-
변경 없이 한 컴퓨터에서 다른 컴퓨터로 데이터를 쉽게 이동할 수 있습니다.
파일 작업
C 언어의 파일에 대해 수행할 수 있는 작업은 다음과 같습니다. -
- 파일 이름 지정.
- 파일 열기.
- 파일에서 읽기.
- 파일에 쓰기.
- 파일을 닫습니다.
구문
파일 열기 및 이름 지정 구문 다음과 같습니다 -
FILE *File pointer;
예를 들어, 파일 * fptr;
File pointer = fopen ("File name”, "mode”); 예를 들어, fptr =fopen("sample.txt", "r")
FILE *fp;
fp = fopen ("sample.txt”, "w”); 파일에서 읽기 구문 다음과 같습니다 -
int fgetc( FILE * fp );// read a single character from a file
파일에 쓰기 구문 다음과 같습니다 -
int fputc( int c, FILE *fp ); // write individual characters to a stream
예시
다음은 파일을 시연하는 C 프로그램입니다 -
#include<stdio.h>
void main(){
//Declaring File//
FILE *femp;
char empname[50];
int empnum;
float empsal;
char temp;
//Opening File and writing into it//
femp=fopen("Employee Details.txt","w");
//Writing User I/p into the file//
printf("Enter the name of employee : ");
gets(empname);
//scanf("%c",&temp);
printf("Enter the number of employee : ");
scanf("%d",&empnum);
printf("Enter the salary of employee : ");
scanf("%f",&empsal);
//Writing User I/p into the file//
fprintf(femp,"%s\n",empname);
fprintf(femp,"%d\n",empnum);
fprintf(femp,"%f\n",empsal);
//Closing the file//
fclose(femp);
//Opening File and reading from it//
femp=fopen("Employee Details.txt","r");
//Reading O/p from the file//
fscanf(femp,"%s",empname);
//fscanf(femp,"%d",&empnum);
//fscanf(femp,"%f",&empsal);
//Printing O/p//
printf("employee name is : %s\n",empname);
printf("employee number is : %d\n",empnum);
printf("employee salary is : %f\n",empsal);
//Closing File//
fclose(femp);
} 출력
위의 프로그램이 실행되면 다음과 같은 결과가 생성됩니다 -
Enter the name of employee : Pinky Enter the number of employee : 20 Enter the salary of employee : 5000 employee name is : Pinky employee number is : 20 employee salary is : 5000.000000