Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C 프로그래밍에서 파일 처리의 기초

<시간/>

파일 처리 프로그램을 사용하여 파일에 데이터를 저장하는 것입니다. C 프로그래밍 언어에서 프로그램은 파일 처리를 사용하여 결과 및 프로그램의 기타 데이터를 파일에 저장합니다. C에서. 또한 프로그램에서 작업하기 위해 파일에서 데이터를 추출/가져올 수 있습니다.

C의 파일에 대해 수행할 수 있는 작업은 다음과 같습니다. -

  • 새 파일 만들기

  • 기존 파일 열기

  • 기존 파일에서 데이터 읽기

  • 파일에 데이터 쓰기

  • 파일의 특정 위치로 데이터 이동

  • 파일 닫기

fopen()을 사용하여 파일 생성 또는 열기

fopen() 함수는 C에서 새 파일을 만들거나 기존 파일을 여는 데 사용됩니다. fopen 함수는 stdio.h에 정의되어 있습니다. 헤더 파일.

이제 새 파일을 만들거나 파일을 여는 구문을 살펴보겠습니다.

file = fopen(“file_name”, “mode”)

이것은 C에서 파일을 열고 생성하기 위한 공통 구문입니다.

매개변수

파일 이름 − fopen 메소드를 사용하여 열거나 생성할 파일의 이름을 지정하는 문자열입니다. 모드:파일을 열 모드를 지정하는 문자열(보통 단일 문자)입니다. C에서 파일을 여는 데 사용할 수 있는 다양한 모드가 있으며 이 문서의 뒷부분에서 모든 모드에 대해 알아볼 것입니다.

파일은 언제 생성되나요?

fopen 함수는 지정된 위치에서 지정된 이름의 파일을 찾지 못할 때 새 파일을 만듭니다. 그렇지 않으면 파일이 발견되면 지정된 모드로 파일이 열립니다.

개념을 명확히 할 수 있는 예제를 살펴보겠습니다. fopen 함수를 사용하여 hello.txt라는 파일을 엽니다. 다음은 성명서입니다.

file = fopen(“hello.txt”, “w”)

이것은 현재 디렉토리에서 hello.txt라는 파일을 검색할 것입니다. 파일이 존재하면 파일을 열 것입니다. 그렇지 않으면 "hello.txt"라는 새 파일을 만들고 쓰기 모드("w"를 사용하여 지정)로 엽니다.

이제 C에서 파일을 읽거나 쓰는 데 사용할 수 있는 모든 유형의 모드와 코드의 샘플 실행을 보여주는 코드 스니펫을 살펴보겠습니다.

모드 ="r" - 읽기용으로 열기, 이 모드는 읽기용으로만 파일을 엽니다.

이 모드는 새 파일을 만들 수 없으며 open()이 NULL을 반환합니다. , 이 모드를 사용하여 새 파일을 만들려고 하면

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "r")){
      printf("File opened successfully in read mode");
   }
   else
   printf("The file is not present! cannot create a new file using r mode");
   fclose(file);
   return 0;
}

출력

File opened successfully in read mode

현재 디렉토리에 hello.txt라는 파일을 생성했지만 다른 파일에 액세스하려고 하면 "파일이 없습니다! r 모드를 사용하여 새 파일을 생성할 수 없습니다.”라고 출력합니다.

모드 ="rb" - 이진 모드에서 읽기 위해 열기, 이 모드는 이진 모드로만 읽기 위해 파일을 엽니다.

이 모드는 새 파일을 만들 수 없으며 open()이 NULL을 반환합니다. , 이 모드를 사용하여 새 파일을 만들려고 하면

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("program.txt", "rb")){
      printf("File opened successfully in read mode");
   }
   else
   printf("The file is not present! cannot create a new file using rb mode");
   fclose(file);
   return 0;
}

출력

파일이 없습니다! rb 모드를 사용하여 새 파일을 만들 수 없습니다.

모드 ="w" - 쓰기 전용으로 열기, 이 모드는 쓰기 전용, 즉 읽기 작업을 수행할 수 없는 현재 디렉토리에 있는 경우 파일을 엽니다. 파일이 현재 디렉토리에 없으면 프로그램은 새 파일을 만들고 쓰기 위해 엽니다.

일부 텍스트가 포함된 파일을 열면 내용을 덮어씁니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("helo.txt", "w")){
      printf("File opened successfully in write mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}

출력

File opened successfully in write mode or a new file is created

여기에서 볼 수 있습니다. 디렉토리에 없는 "helo.txt" 파일을 열려고 시도했지만 "helo.txt"라는 파일을 생성했기 때문에 함수는 여전히 성공 메시지를 반환했습니다.

모드 ="wb" - 바이너리 모드로 쓰기 위해 열기, 이 모드는 바이너리 모드로 쓰기 위해 현재 디렉토리에 있는 경우 파일을 엽니다. 즉, 읽기 작업을 수행할 수 없습니다. 파일이 현재 디렉토리에 없으면 프로그램은 새 파일을 만들고 바이너리 모드로 쓰기 위해 엽니다.

일부 텍스트가 포함된 파일을 열면 내용을 덮어씁니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "wb")){
      printf("File opened successfully in write in binary mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}

출력

바이너리 모드에서 쓰기로 파일이 성공적으로 열렸거나 새 파일이 생성되었습니다.

모드 ="a" - 추가 전용으로 열기, 이 모드는 쓰기 전용, 즉 읽기 작업을 수행할 수 없는 현재 디렉토리에 있는 경우 파일을 엽니다. 파일이 현재 디렉터리에 없으면 프로그램은 새 파일을 만들고 쓰기 위해 엽니다. 일부 텍스트가 포함된 파일을 열면 내용을 덮어쓰지 않습니다. 대신 새 텍스트가 파일의 기존 텍스트 뒤에 추가됩니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "a")){
      printf("File opened successfully in append mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}

출력

File opened successfully in append mode or a new file is created

모드 ="ab" - 바이너리로 추가를 위해 열기, 이 모드는 바이너리로 쓰기 위해 현재 디렉토리에 있는 경우 파일을 엽니다. 즉, 읽기 작업을 수행할 수 없습니다. 파일이 현재 디렉토리에 없으면 프로그램은 새 파일을 만들고 바이너리로 쓰기 위해 엽니다.

일부 텍스트가 포함된 파일을 열면 내용을 덮어쓰지 않습니다. 대신 새 텍스트가 파일의 기존 텍스트 뒤에 추가됩니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "ab")){
      printf("File opened successfully in append in binary mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}

출력

File opened successfully in append in binary mode or a new file is created

모드 ="r+" - 읽기 및 쓰기 모두를 위해 열기, 이 모드는 읽기 및 쓰기 목적으로 파일을 엽니다. 즉, 파일에 대해 읽기 및 쓰기 작업을 모두 수행할 수 있습니다.

이 모드는 새 파일을 만들 수 없으며 open()이 NULL을 반환합니다. , 이 모드를 사용하여 새 파일을 만들려고 하면

텍스트가 포함된 파일을 열고 무언가를 쓰면 내용을 덮어씁니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "r+")){
      printf("File opened successfully in read and write both");
   }
   else
   printf("The file is not present! cannot create a new file using r+ mode");
   fclose(file);
   return 0;
}

출력

File opened successfully in read and write both

현재 디렉토리에 hello.txt라는 파일을 생성했지만 다른 파일에 액세스하려고 하면 "파일이 없습니다! r+ 모드를 사용하여 새 파일을 생성할 수 없습니다.”라고 출력합니다.

모드 ="rb+" - 이진 모드에서 읽기 위해 열기, 이 모드는 이진 모드로만 읽기 위해 파일을 엽니다.

이 모드는 새 파일을 만들 수 없으며 open()은 NULL을 반환합니다. 이 모드를 사용하여 새 파일을 만들려고 하면

텍스트가 포함된 파일을 열고 무언가를 쓰면 내용을 덮어씁니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("program.txt", "rb+")){
      printf("File opened successfully in read mode");
   }
   else
   printf("The file is not present! cannot create a new file using rb+ mode");
   fclose(file);
   return 0;
}

출력

The file is not present! cannot create a new file using rb+ mode

모드 ="w" - 쓰기 및 읽기를 위해 열기, 이 모드는 쓰기 및 읽기 작업 모두를 위해 현재 디렉토리에 있는 경우 파일을 엽니다. 파일이 현재 디렉토리에 없으면 프로그램은 새 파일을 만들고 읽고 쓰기 위해 엽니다.

일부 텍스트가 포함된 파일을 열면 내용을 덮어씁니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("helo.txt", "w+")){
      printf("File opened successfully in read-write mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}

출력

File opened successfully in read-write mode or a new file is created

여기에서 볼 수 있습니다. 디렉토리에 없는 "helo.txt" 파일을 열려고 시도했지만 "helo.txt"라는 파일을 생성했기 때문에 함수는 여전히 성공 메시지를 반환했습니다.

Mode ="wb+" :바이너리 모드에서 쓰기와 읽기를 위해 열림

바이너리 모드. 파일이 현재 디렉토리에 없으면 프로그램은 새 파일을 만들고 이진 모드에서 읽고 쓸 수 있도록 엽니다. 일부 텍스트가 포함된 파일을 열면 내용을 덮어씁니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "wb+")){
      printf("File opened successfully in read-write in binary mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}

출력

File opened successfully in read-write in binary mode or a new file is created

모드 ="a+" - 읽기 및 추가를 위해 열기, 이 모드는 읽기와 쓰기 모두를 위해 현재 디렉토리에 있는 경우 파일을 엽니다. 파일이 현재 디렉토리에 없으면 프로그램은 새 파일을 만들고 읽고 쓰기 위해 엽니다.

일부 텍스트가 포함된 파일을 열면 내용을 덮어쓰지 않습니다. 대신 새 텍스트가 파일의 기존 텍스트 뒤에 추가됩니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "a+")){
      printf("File opened successfully in read-append mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}

출력

읽기-추가 모드에서 파일이 성공적으로 열렸거나 새 파일이 생성되었습니다.

모드 ="ab+" - 읽기용으로 열고 바이너리로 추가, 이 모드는 바이너리로 읽고 쓰기 위해 현재 디렉토리에 있는 경우 파일을 엽니다. 파일이 현재 디렉토리에 없으면 프로그램은 새 파일을 만들고 이진 파일을 읽고 쓸 수 있도록 엽니다. 일부 텍스트가 포함된 파일을 열면 내용을 덮어쓰지 않습니다. 대신 새 텍스트가 파일의 기존 텍스트 뒤에 추가됩니다.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "ab+")){
      printf("File opened successfully in read-append in binary mode or a new file is created");
   }
   else
   printf("Error!”);
   fclose(file);
   return 0;
}

출력

File opened successfully in read-append mode or a new file is created

기존 파일에서 데이터 읽기

fscanf() 및 fgets() 및 fgetc() 함수를 사용하여 c에서 파일의 내용을 읽을 수 있습니다. 모두 파일의 내용을 읽는 데 사용됩니다. 각 기능의 작동을 살펴보겠습니다 −

fscanf()

fscanf() 함수는 파일에서 문자 집합, 즉 문자열을 읽는 데 사용됩니다. 파일의 모든 내용을 읽을 때 EOF를 반환합니다.

구문

int fscanf(FILE *stream, const char *charPointer[])

매개변수

FILE *stream: the pointer to the opened file.
const char *charPointer[]: string of character.

예시

#include <stdio.h>
int main(){
   FILE * file;
   char str[500];
   if (file = fopen("hello.txt", "r")){
         while(fscanf(file,"%s", str)!=EOF){
         printf("%s", str);
      }
   }
   else
   printf("Error!”);
   fclose(file);
   return 0;
}

출력

LearnprogrammingattutorialsPoint

fgets()

C의 fget() 함수는 스트림에서 문자열을 읽는 데 사용됩니다.

구문

char* fgets(char *string, int length, FILE *stream)

매개변수

char *string: It is a string which will store the data from the string.
int length: It is an int which gives the length of string to be considered.
FILE *stream: It is the pointer to the opened file.

예시

#include <stdio.h>
int main(){
   FILE * file;
   char str[500];
   if (file = fopen("hello.txt", "r")){
      printf("%s", fgets(str, 50, file));
   }
   fclose(file);
   return 0;
}

출력

Learn programming at tutorials Point

fgetc()

C의 fgetc() 함수는 파일에서 단일 문자를 반환하는 데 사용됩니다. 파일에서 문자를 가져와서 파일 끝에 EOF를 반환합니다.

구문

char* fgetc(FILE *stream)

매개변수

FILE *stream: It is the pointer to the opened file.

예시

#include <stdio.h>
int main(){
   FILE * file;
   char str;
   if (file = fopen("hello.txt", "r")){
      while((str=fgetc(file))!=EOF)
      printf("%c",str);
   }
   fclose(file);
   return 0;
}

출력

Learn programming at tutorials Point

C 파일에 데이터 쓰기

fprintf(), fputs(), fputc() 함수를 사용하여 C의 파일에 데이터를 쓸 수 있습니다. 모두 파일에 내용을 쓰는 데 사용됩니다.

각 기능의 작동 방식을 살펴보겠습니다 -

fprintf()

fprintf() 함수는 파일에 데이터를 쓰는 데 사용됩니다. 파일에 일련의 문자를 씁니다.

구문

int fprintf(FILE *stream, char *string[])

매개변수

FILE for *stream: It is the pointer to the opened file.
char *string[]: It is the character array that we want to write in the file.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "w")){
      if(fprintf(file, "tutorials Point”) >= 0)
      printf("Write operation successful");
   }
   fclose(file);
   return 0;
}

출력

Write operation successful

fputf()

C의 fputf() 함수를 사용하여 파일에 쓸 수 있습니다. 파일에 한 줄(문자 줄)을 쓸 때 사용합니다.

구문

int fputs(const char *string, FILE *stream)

매개변수

Constant char *string[]: It is the character array that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "w")){
      if(fputs("tutorials Point", file) >= 0)
      printf("String written to the file successfully...");
   }
   fclose(file);
   return 0;
}

출력

String written to the file successfully…

fputc()

fputc() 함수는 파일에 단일 문자를 쓰는 데 사용됩니다.

구문

int fputc(char character , FILE *stream)

매개변수

char character : It is the character that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.

예시

#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "w")){
      fputc('T', file);
   }
   fclose(file);
   return 0;
}

출력

‘T’ is written to the file.

fclose()

fclose() 함수는 열린 파일을 닫는 데 사용됩니다. 적용한 작업을 저장하려면 작업을 수행한 후 파일을 닫아야 합니다.

구문

fclose(FILE *stream)

매개변수

FILE for *stream: It is the pointer to the opened file.

예시

#include <stdio.h>
int main(){
   FILE * file;
   char string[300];
   if (file = fopen("hello.txt", "a+")){
      while(fscanf(file,"%s", string)!=EOF){
         printf("%s", string);
      }
      fputs("Hello", file);
   }
   fclose(file);
   return 0;
}

출력

Learn programming at tutorials Point

파일 포함

Learn programming at Tutorials PointHello