반응형
C++의 <fstream>
헤더에 정의된 ifstream
와 ofstream
클래스는 파일의 입력 및 출력 작업을 담당합니다. ifstream
는 파일로부터 데이터를 읽는 데 사용되고, ofstream
는 파일에 데이터를 쓰는 데 사용됩니다. 아래에 각 클래스의 기본 사용법을 설명하겠습니다.
ifstream 사용 방법:
- 헤더 파일을 포함시킵니다:
#include <fstream>
ifstream
객체를 선언하고 파일을 엽니다:ifstream inputFile("파일명");
- 파일을 열었는지 확인합니다:
if (inputFile.is_open()) { // 파일이 열렸을 때 수행할 작업을 여기에 작성합니다. } else { // 파일을 열지 못했을 때 수행할 작업을 여기에 작성합니다. }
- 파일에서 데이터를 읽습니다:
int number; inputFile >> number; // 파일에서 데이터를 읽어 변수에 저장합니다.
- 파일을 닫습니다:
inputFile.close();
ofstream 사용 방법:
- 헤더 파일을 포함시킵니다:
#include <fstream>
ofstream
객체를 선언하고 파일을 엽니다:ofstream outputFile("파일명");
- 파일을 열었는지 확인합니다:
if (outputFile.is_open()) { // 파일이 열렸을 때 수행할 작업을 여기에 작성합니다. } else { // 파일을 열지 못했을 때 수행할 작업을 여기에 작성합니다.
- 파일에 데이터를 씁니다:
int number = 42; outputFile << number; // 변수의 값을 파일에 씁니다.
- 파일을 닫습니다:
outputFile.close();
위의 예시에서 "파일명"은 작업하려는 파일의 경로와 이름으로 대체되어야 합니다. 또한 파일을 여는 동작은 실패할 수 있으므로 파일이 제대로 열렸는지 확인하는 것이 좋습니다.
이와 같이 ifstream
및 ofstream
을 사용하여 C++에서 파일의 입력 및 출력 작업을 수행할 수 있습니다.
아래는 파일 이름, str1, str2 을 인자로 받아 그 파일 안의 str1을 str2로 바꾸는 프로그램이다.
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: donghyk2 <donghyk2@student.42.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/07/04 14:38:44 by donghyk2 #+# #+# */
/* Updated: 2023/07/04 17:30:59 by donghyk2 ### ########.fr */
/* */
/* ************************************************************************** */
#include <iostream>
#include <fstream>
#include <string>
void ftError(std::string message) {
std::cout << message << std::endl;
exit(1);
}
std::string getSumOfString(std::string s1, std::string s2) {
return (s1 + s2);
}
std::string getReplacedLine(std::string line, std::string src, std::string dst) {
for (int i = 0; i + src.size() <= line.size(); i++)
if (line.substr(i, src.size()) == src)
line = line.substr(0, i) + dst + line.substr(i + src.size(), line.size() - (i + src.size()));
return line;
}
int main(int argc, char **argv) {
if (argc != 4)
ftError("wrong arg");
std::ifstream input(argv[1]);
std::ofstream output(getSumOfString(argv[1], ".replace"));
std::string line;
if (input.fail() || output.fail())
ftError("iofstream error");
while (std::getline(input, line)) {
output << getReplacedLine(line, argv[2], argv[3]);
if (!input.eof())
output << std::endl;
}
input.close();
}
반응형
'<language> > c++' 카테고리의 다른 글
c++ class 상속, 가상함수 테이블, 추상클래스 (0) | 2023.08.07 |
---|---|
c++ 레퍼런스(참조자) (8) | 2023.07.06 |
c++ 동적할당 (0) | 2023.07.06 |
cpp split (0) | 2023.05.29 |
STL 해시 (0) | 2023.04.06 |