파일은 디스크의 물리적 저장 위치이고 디렉토리는 파일을 구성하는 데 사용되는 논리적 경로입니다. 디렉토리 내에 파일이 있습니다.
파일에 대해 수행할 수 있는 세 가지 작업은 다음과 같습니다. -
- 파일을 엽니다.
- 파일 처리(읽기, 쓰기, 수정).
- 파일을 저장하고 닫습니다.
프로그램
다음은 짝수, 홀수 및 소수를 별도의 파일에 저장하는 C 프로그램입니다. -
#include <stdio.h>
#include <stdlib.h>
/* Function declarations */
int even(const int num);
int prime(const int num);
int main(){
FILE * fptrinput,
* fptreven,
* fptrodd,
* fptrprime;
int num, success;
fptrinput = fopen("numbers.txt", "r");
fptreven = fopen("even-numbers.txt" , "w");
fptrodd = fopen("odd-numbers.txt" , "w");
fptrprime= fopen("prime-numbers.txt", "w");
if(fptrinput == NULL || fptreven == NULL || fptrodd == NULL || fptrprime == NULL){
/* Unable to open file hence exit */
printf("Unable to open file.\n");
exit(EXIT_FAILURE);
}
/* File open success message */
printf("File opened successfully. Reading integers from file. \n\n");
// Read an integer and store read status in success.
while (fscanf(fptrinput, "%d", &num) != -1){
if (prime(num))
fprintf(fptrprime, "%d\n", num);
else if (even(num))
fprintf(fptreven, "%d\n", num);
else
fprintf(fptrodd, "%d\n", num);
}
fclose(fptrinput);
fclose(fptreven);
fclose(fptrodd);
fclose(fptrprime);
printf("Data written successfully.");
return 0;
}
int even(const int num){
return !(num & 1);
}
int prime(const int num){
int i;
if (num < 0)
return 0;
for ( i=2; i<=num/2; i++ ) {
if (num % i == 0) {
return 0;
}
}
return 1;
} 출력
위의 프로그램이 실행되면 다음과 같은 결과가 생성됩니다 -
File opened successfully. Reading integers from file. Data written successfully.
설명
다음은 짝수, 홀수 및 소수를 별도의 파일에 저장하는 데 사용되는 프로그램에 대한 설명입니다. -
Input file: numbers.txt file contains: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Which is open in read mode (already exists file) Separated even, odd and prime numbers in separate file after execution even-numbers.txt contains: 4 6 8 10 12 14 16 odd-numbers.txt contains: 9 15 prime-numbers.txt contains: 1 2 3 5 7 11 13 17