C 언어에서는 문자 배열의 크기를 런타임 중에 늘릴 수 없다. 하지만 C++에서 string을 사용하면, 필요에 따라 길이를 조절할 수 있으며 문자열 수정에 관한 여러 API도 사용 가능하다.
// Main.cpp
#include <iostream>
#include <string>
int main(void)
{
std::string FirstName;
std::string LastName;
std::string FullName;
/* in C.
char FirstName[20];
char LastName[20];
char FullName[20];
*/
// 대입 연산과 이어붙이기 연산이 가능합니다.
std::cout << "What is your first name? ";
std::cin >> FirstName;
FullName = FirstName;
std::cout << "What is your last name? ";
std::cin >> LastName;
FullName = FirstName + " " + LastName;
std::cout << FullName << std::endl;
std::string FriendFullName = "Lee JH";
std::cout << "Your full name is " << FullName << '(' << FullName.length() << ')' << std::endl;
std::cout << "Friend's full name is " << FriendFullName << '(' << FriendFullName.length() << ')' << std::endl;
if (FullName == FriendFullName) // 길이 비교는 아닙니다.
{
std::cout << "Same name." << std::endl;
}
else if (FullName < FriendFullName)
{
std::cout << "Friend name is prior in lexical-order." << std::endl;
}
else
{
std::cout << "Your name is prior in lexical-order." << std::endl;
}
return 0;
}
File I/O
ifstream: 파일 입력 스트림
// In C++
ifstream InputFile;
InputFile.open("HelloFile.txt"); // 읽기 전용으로 파일을 오픈.
// In C.
FILE* InputFile;
InputFile = fopen("HelloFile.txt", "r");
ofstream: 파일 출력 스트림
// In C++
ofstream OutputFile;
OutputFile.open("HelloFile.txt"); // 쓰기 전용으로 파일을 오픈.(파일이 없으면 만들어 줍니다)
// In C.
FILE* OutputFile;
OutputFile = fopen("HelloFile.txt", "w");
fstream: 파일 입력 및 출력 스트림
// In C++
fstream FileStream;
FileStream.open("HelloFile.txt"); // 읽기와 쓰기 범용으로 파일을 오픈.
// In C.
FILE* FilePointer;
FilePointer = fopen("HelloFile.txt", "r+"); // w+와 다름. w+는 기존 파일의 내용을 삭제합니다.
파일 스트림에 읽고 쓰는 방법
텍스트 모드에서는 << 연산자와 >> 연산자로 읽고 쓰기가 가능하고, 바이너리 모드에서는 read() 함수와 write() 함수로 읽고 쓰기가 가능하다.
open()
파일을 열 때 사용하는 함수
열기 모드
std::ios_base::in
- 파일을 읽기 모드로 연다
std::ios_base::out
- 파일을 쓰기 모드로 연다.
std::ios_base::app
- 파일 끝에 내용을 덧붙이는 모드로 연다.
std::ios_base::binary
- 파일을 열 때 바이너리 모드로 연다.
std::ios_base::trunc
- 파일이 열릴 때 기존 내용을 다 지운다.
InputFile.open("HelloFile.txt", ios_base::in | ios_base::binary);
// 위와 같이 조합할 수 있다.
cplusplus.com에들어가면 C++ 라이브러리 정보를 볼 수 있다.
is_open()
파일이 열려있는지 확인할 수 있다.
fstream FileStream;
FileStream.open("HelloFile.txt");
if (FileStream.is_open() == true)
{
...
}
close()
파일을 닫을 때 사용하는 함수
// In C++
ifstream InputFile;
InputFile.close();
// 사실 InputFile이 선언된 스코프를 벗어날 때 자동으로 close() 되긴 합니다.
// In C
FILE *FilePointer;
fclose(FilePointer);
키보드에서 입력받아서 파일로 출력
// Main.cpp
#include <iostream>
#include <fstream>
#include <string> // getline()
int main(void)
{
std::ofstream OutFile;
OutFile.open("HelloFile.txt");
if (OutFile.is_open() == false)
{
std::cout << "Failed to open file." << std::endl;
return 0;
}
std::string Line;
std::getline(std::cin, Line);
if (std::cin.fail() == false)
{
OutFile << Line << std::endl;
// endl; 하면 개행 후 해당 스트림의 flush까지 진행됩니다.
// OutFile << Line;을 하게 되면, Line에 적힌 내용이 곧바로 파일에 적히지 않을 수 있습니다.
// 그 대신 "버퍼"라는 임시 저장소에 적혀있게 됩니다.
// 만약 OutFile << Line << std::endl;이라고 하면,
// Line의 내용이 버퍼에 적힌 뒤 endl에 의해 비로소 파일에 적히게 됩니다.
// 즉 flush란, 해당 버퍼(스트림)에 적혀 있는 내용을 파일에 쏟아부어서 비우는 동작입니다.
}
if (OutFile.is_open() == true)
{
OutFile.close();
}
return 0;
}
파일에서 입력받아 콘솔로 출력
// Main.cpp
#include <iostream>
#include <fstream>
int main(void)
{
std::ifstream InputFile;
InputFile.open("HelloFile.txt");
if (InputFile.is_open() == false)
{
std::cout << "Failed to open file." << std::endl;
return 0;
}
char Character;
while (true)
{
//InputFile >> Character; // 이렇게 읽으면 띄어쓰기, 개행문자 등은 무시됨
InputFile.get(Character);
if (InputFile.fail() == true)
{
break;
}
std::cout << Character;
}
if (InputFile.is_open() == true)
{
InputFile.close();
}
return 0;
}
이진 파일(bin) 쓰기
// Main.cpp
#include <iostream>
#include <fstream>
enum { LENGTH = 32 };
int main(void)
{
std::ofstream OutputFileStream;
OutputFileStream.open("HelloBinary.bin", std::ios_base::out | std::ios_base::binary);
if (OutputFileStream.is_open() == false)
{
std::cout << "Failed to open file." << std::endl;
return 0;
}
char Buffer[LENGTH] = "Parkthy";
OutputFileStream.write(Buffer, LENGTH);
if (OutputFileStream.is_open() == true)
{
OutputFileStream.close();
}
return 0;
}
이진 파일 읽기
// Main.cpp
#include <iostream>
#include <fstream>
enum { LENGTH = 32 };
int main(void)
{
std::ifstream InputFile;
InputFile.open("HelloBinary.bin", std::ios_base::in | std::ios_base::binary);
if (InputFile.is_open() == false)
{
std::cout << "Failed to open file." << std::endl;
return 0;
}
char Buffer[LENGTH] = { '\0', };
InputFile.read(Buffer, LENGTH);
std::cout << Buffer << std::endl;
if (InputFile.is_open() == true)
{
InputFile.close();
}
return 0;
}'코딩 학습 > C와 C++' 카테고리의 다른 글
| C++ 기초 - 템플릿 프로그래밍 (0) | 2026.04.08 |
|---|---|
| C++ 기초 - Casting, inline 키워드, static 키워드, 예외 처리 (1) | 2026.04.08 |
| C++ 기초 - 복사 생성자와 오버로딩 (0) | 2026.04.07 |
| C++ 기초 - 생성자와 소멸자 (0) | 2026.04.06 |
| C++ 기초 - Console IO (0) | 2026.04.03 |