프로그래밍/C++
C++ 파일 입출력(ofstream, ifstream) Window전용
Hwan2
2020. 6. 4. 20:15
반응형
C++에서 파일 입출력할 때 쓰이는 ofstream과 ifstream에 대해 알아보도록 하겠습니다.(Windows)
ofstream(output으로 write할 때 쓰임) : http://www.cplusplus.com/reference/fstream/ofstream/
ifstream(input으로 read할 때 쓰임) : http://www.cplusplus.com/reference/fstream/ifstream/
사용법
#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>
#include <shlobj_core.h>
using namespace std;
string text = "In 1979, Bjarne Stroustrup, a Danish computer scientist, began work on \"C with Classes\", \
the predecessor to C++.[15] The motivation for creating a new language originated from Stroustrup's experience\
in programming for his PhD thesis. Stroustrup found that Simula had features that were very helpful for large \
software development, but the language was too slow for practical use, while BCPL was fast but too low-level \
to be suitable for large software development. When Stroustrup started working in AT&T Bell Labs, he had the \
problem of analyzing the UNIX kernel with respect to distributed computing. Remembering his Ph.D. experience, \
Stroustrup set out to enhance the C language with Simula-like features.[16] \
C was chosen because it was general-purpose, fast, portable and widely used. As well as C and Simula's \
influences, other languages also influenced this new language, including ALGOL 68, Ada, CLU and ML.\n\n\
Initially, Stroustrup's \"C with Classes\" added features to the C compiler, Cpre, including classes, \
derived classes, strong typing, inlining and default arguments.[17]\n\n\
In 1982, Stroustrup started to develop a successor to C with Classes, which he named \"C++\" \
(++being the increment operator in C) after going through several other names.New features were added, \
including virtual functions, function nameand operator overloading, references, constants,\
type - safe free - store memory allocation(new / delete), improved type checking, and BCPL \
style single - line comments with two forward slashes(//). Furthermore, Stroustrup developed a new,\
standalone compiler for C++, Cfront.\n\n\
In 1985, the first edition of The C++ Programming Language was released, which became the definitive \
reference for the language, as there was not yet an official standard.[18] The first commercial \
implementation of C++ was released in October of the same year.[15]\n\n\
In 1989, C++ 2.0 was released, followed by the updated second edition of The\
C++ Programming Language in 1991.[19] New features in 2.0 included multiple inheritance, \
abstract classes, static member functions, const member functions, and protected members.In 1990, \
The Annotated C++ Reference Manual was published.This work became the basis for the future standard.Later \
feature additions included templates, exceptions, namespaces, new casts, and a Boolean type.";
void create_filename(PWSTR path, WCHAR* cp_path, string s) {
int i = 0;
while (path[i] != '\0') cp_path[i] = path[i++];
for_each(s.begin(), s.end(), [&](char& c) { cp_path[i++] = c; });
cp_path[i] = '\0';
}
int main(void) {
PWSTR path = NULL; WCHAR cp_path[100];
SHGetKnownFolderPath(FOLDERID_Desktop, 0, NULL, &path); //바탕화면 경로 가져오기.
create_filename(path, cp_path, "\\text.txt");
ofstream writeFile(cp_path);
if (writeFile.is_open()) { //open으로 대체 가능
writeFile << text; // == writeFile.write(text.c_str(), text.size());
writeFile.close();
}
ifstream readFile(cp_path);
if (readFile.is_open()) { //open으로 대체 가능
string line;
while (getline(readFile, line)) {
cout << line << endl;
}
readFile.close();
}
/* //한개의 단어씩 읽어올 때.
char c = openFile.get();
while (openFile.good()) {
std::cout << c;
c = openFile.get();
}
openFile.close();
*/
CoTaskMemFree(path);
return 0;
}
실행 결과
설명
해당 코드가 실행되면 사용자 바탕화면에 "text.txt"라는 텍스트 파일이 생기면서 string text에 있는 문자열이 저장됩니다.
getline()은 string에 정의되어 있는 함수로 파일의 끝 혹은 개행(\n)이 나올때 까지 문자를 읽고 string매개 변수에 복사합니다.
SHGetKnownFolderPath()함수에 대한 설명은 여기를 참조해 주세요.
반응형