파일 처리는 데이터를 컴퓨터에 영구적으로 저장하는 데 사용됩니다. 파일 처리를 사용하면 데이터를 보조 메모리(하드 디스크)에 저장할 수 있습니다.
파일 처리를 달성하는 방법
파일 처리를 위해서는 다음 단계를 따라야 합니다.
1단계 - 파일 이름 지정
2단계 - 파일 열기
3단계 - 파일에 데이터 쓰기
4단계 - 파일에서 데이터 읽기
5단계 - 파일을 닫습니다.
C++의 스트림 :-
우리는 실행 프로그램에 입력을 제공하고 실행 프로그램은 출력을 반환합니다. 실행 프로그램에 입력으로 제공되는 바이트 시퀀스와 실행 프로그램에서 출력으로 제공되는 바이트 시퀀스를 스트림이라고 합니다. 즉, 스트림은 시퀀스의 데이터 흐름일 뿐입니다.
실행 프로그램과 키보드, 모니터 등의 장치 간의 입출력 작업을 콘솔 I/O 작업이라고 합니다. 실행 중인 프로그램과 파일 간의 입출력 작업을 디스크 I/O 작업이라고 합니다.
파일 스트림 작업을 위한 클래스:-
C++의 I/O 시스템에는 파일 처리 방법을 정의하는 클래스 세트가 포함되어 있습니다. 여기에는 ifstream, ofstream 및 fstream 클래스가 포함됩니다. 이러한 클래스는 fstream 및 해당 iostream 클래스에서 파생됩니다. 디스크 파일을 관리하도록 설계된 이러한 클래스는 fstream에 선언되므로 파일을 사용하는 모든 프로그램에 이 파일을 포함해야 합니다.
1. iOS:-
- ios는 입력 출력 스트림을 나타냅니다.
- 이 클래스는 이 클래스 계층 구조에 있는 다른 클래스의 기본 클래스입니다.
- 이 클래스에는 입력 및 출력 작업을 위해 다른 모든 파생 클래스에서 사용하는 필수 기능이 포함되어 있습니다.
2. 아이스트림:-
- istream은 입력 스트림을 나타냅니다.
- 이 클래스는 'ios' 클래스에서 파생됩니다.
- 이 클래스는 입력 스트림을 처리합니다.
- 이 클래스에는 추출 연산자(>>)가 오버로드되어 파일에서 프로그램 실행까지의 입력 스트림을 처리합니다.
- 이 클래스는 get(), getline() 및 read()와 같은 입력 함수를 선언합니다.
3. 반대편:-
- ostream은 출력 스트림을 나타냅니다.
- 이 클래스는 'ios' 클래스에서 파생됩니다.
- 이 클래스는 출력 스트림을 처리합니다.
- 삽입 연산자(<<)는 프로그램 실행에서 파일로의 출력 스트림을 처리하기 위해 이 클래스에 오버로드됩니다.
- 이 클래스는 put() 및 write()와 같은 출력 함수를 선언합니다.
4. 스트림버프:-
개발자 모드를 비활성화하는 방법
- 이 클래스에는 입력 및 출력 스트림을 관리하는 데 사용되는 버퍼를 가리키는 포인터가 포함되어 있습니다.
5. fstreambase:-
- 이 클래스는 파일 스트림에 공통적인 작업을 제공합니다. fstream, ifstream 및 ofstream 클래스의 기반 역할을 합니다.
- 이 클래스에는 open() 및 close() 함수가 포함되어 있습니다.
6. ifstream:-
- 이 클래스는 입력 작업을 제공합니다.
- 여기에는 기본 입력 모드의 open() 함수가 포함되어 있습니다.
- istream에서 get(), getline(), read(), seekg() 및 Tellg() 함수를 상속합니다.
7. 오브스트림:-
- 이 클래스는 출력 작업을 제공합니다.
- 여기에는 기본 출력 모드의 open() 함수가 포함되어 있습니다.
- ostream에서 put(), write(), Seekp() 및 Tellp() 함수를 상속합니다.
8. fstream:-
- 이 클래스는 동시 입력 및 출력 작업을 지원합니다.
- iostream을 통해 istream 및 ostream 클래스의 모든 기능을 상속합니다.
9. 파일버프:-
- 그 목적은 파일 버퍼를 읽고 쓰도록 설정하는 것입니다.
- 파일 버퍼 멤버 함수를 사용하여 파일 길이를 결정할 수도 있습니다.
C++에서는 fstream 헤더파일에서 사용할 수 있는 fstream, ifstream, ofstream 세 가지 클래스를 사용하여 파일을 주로 처리합니다.
스트림: 파일에 쓰기 위한 스트림 클래스
ifstream: 파일에서 읽을 스트림 클래스
fstream: 파일을 읽고 쓰기 위한 스트림 클래스입니다.

이제 읽기 또는 쓰기 작업을 위해 특정 파일을 여는 첫 번째 단계입니다. 우리는 다음과 같이 파일을 열 수 있습니다.
1. 객체 생성 시 생성자에 파일 이름 전달
2. 개방형 방법 사용
예를 들어
생성자를 사용하여 파일 열기
ifstream (const char* 파일 이름, ios_base::openmode 모드 = ios_base::in);
ifstream fin(파일 이름, openmode) 기본적으로 openmode = ios::in
ifstream fin(파일명);open 메소드를 사용하여 파일 열기
기본 생성자 호출
ifstream 끝;
fin.open(파일명, 오픈모드)
fin.open(파일명);
모드:
| 멤버 상수 | 의미하다 | 입장 |
|---|---|---|
| 안에 * | 입력 | 읽기 위해 파일 열기: 내부 스트림 버퍼는 입력 작업을 지원합니다. |
| 밖으로 | 산출 | 쓰기 위해 파일 열기: 내부 스트림 버퍼는 출력 작업을 지원합니다. |
| 바이너리 | 바이너리 | 작업은 텍스트가 아닌 바이너리 모드로 수행됩니다. |
| 먹었다 | 끝에 | 출력 위치는 파일 끝에서 시작됩니다. |
| 앱 | 추가 | 모든 출력 작업은 파일 끝에서 발생하며 기존 내용에 추가됩니다. |
| 트렁크 | 잘리다 | 파일을 열기 전에 파일에 있던 모든 내용은 삭제됩니다. |
기본 개방 모드:
| ifstream | iOS::에서 |
| 스트림의 | iOS::아웃 |
| fstream | iOS::인 | iOS::아웃 |
문제 설명 : C++에서 파일을 읽고 씁니다.
예:
Input : Welcome in techcodeview.com. Best way to learn things. -1 Output : Welcome in techcodeview.com. Best way to learn things.>
아래는 다음을 사용하여 구현한 것입니다. ifstream 및 ofstream 클래스 .
C++
/* File Handling with C++ using ifstream & ofstream class object*/> /* To write the Content in File*/> /* Then to read the content of file*/> #include> /* fstream header file for ifstream, ofstream,> >fstream classes */> #include> using> namespace> std;> // Driver Code> int> main()> {> >// Creation of ofstream class object> >ofstream fout;> >string line;> >// by default ios::out mode, automatically deletes> >// the content of file. To append the content, open in ios:app> >// fout.open('sample.txt', ios::app)> >fout.open(>'sample.txt'>);> >// Execute a loop If file successfully opened> >while> (fout) {> >// Read a Line from standard input> >getline(cin, line);> >// Press -1 to exit> >if> (line ==>'-1'>)> >break>;> >// Write line in file> >fout << line << endl;> >}> >// Close the File> >fout.close();> >// Creation of ifstream class object to read the file> >ifstream fin;> >// by default open mode = ios::in mode> >fin.open(>'sample.txt'>);> >// Execute a loop until EOF (End of File)> >while> (getline(fin, line)) {> > >// Print line (read from file) in Console> >cout << line << endl;> >}> >// Close the file> >fin.close();> >return> 0;> }> |
>
>
시간 복잡도: O(n)
보조 공간: O(1)
아래는 다음을 사용하여 구현한 것입니다. fstream 클래스 .
C++
/* File Handling with C++ using fstream class object */> /* To write the Content in File */> /* Then to read the content of file*/> #include> /* fstream header file for ifstream, ofstream,> >fstream classes */> #include> using> namespace> std;> // Driver Code> int> main()> {> >// Creation of fstream class object> >fstream fio;> >string line;> >// by default openmode = ios::in|ios::out mode> >// Automatically overwrites the content of file, To append> >// the content, open in ios:app> >// fio.open('sample.txt', ios::in|ios::out|ios::app)> >// ios::trunc mode delete all content before open> >fio.open(>'sample.txt'>, ios::trunc | ios::out | ios::in);> >// Execute a loop If file successfully Opened> >while> (fio) {> >// Read a Line from standard input> >getline(cin, line);> >// Press -1 to exit> >if> (line ==>'-1'>)> >break>;> >// Write line in file> >fio << line << endl;> >}> >// Execute a loop until EOF (End of File)> >// point read pointer at beginning of file> >fio.seekg(0, ios::beg);> >while> (fio) {> >// Read a Line from File> >getline(fio, line);> >// Print line in Console> >cout << line << endl;> >}> >// Close the file> >fio.close();> >return> 0;> }> |
>
>
시간 복잡도: O(n)
보조 공간: O(1)
C++
정수를 문자열로
Q: write a single file handling program in c++ to reading and writing data on a file.> #include> #include> > using> namespace> std;> main()> {> >int> rno,fee;> >char> name[50];> > >cout<<>'Enter the Roll Number:'>;> >cin>>아노;> > >cout<<>'
Enter the Name:'>;> >cin>>이름;> > >cout<<>'
Enter the Fee:'>;> >cin>>수수료;> > >ofstream fout(>'d:/student.doc'>);> > >fout<' '<' '/write data to the file student fout.close(); ifstream fin('d:/student.doc'); fin>>rno>>이름>>수수료; //파일에서 데이터를 읽습니다. Student fin.close(); 시합<' '<' '< return 0; }> |
>
>
시간 복잡도: O(1)
보조 공간: O(1)
C++
// Q: WA C++ file handling program to read data from the file called student.doc> #include> #include> using> namespace> std;> main()> {> >int> rno,fee;> >char> name[50];> > >ifstream fin(>'d:/student.doc'>);> > >fin>>rno>>이름>>수수료;>//read data from the file student> > >fin.close();> > >cout<' '<' '< return 0; }> |
>
>
시간 복잡도: O(1)
보조공간 : O(50)