Skip to content

Commit ff1985e

Browse files
committed
add fstream demo
1 parent f1b21a0 commit ff1985e

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

CMakeLists.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
1111
add_subdirectory(WritingFile)
1212
add_subdirectory(ReadingFile)
1313
add_subdirectory(AppendingFile)
14-
add_subdirectory(BinaryFile)
14+
add_subdirectory(BinaryFile)
15+
add_subdirectory(FileRW)

FileRW/CMakeLists.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
project(FileRW)
2+
3+
add_executable(${PROJECT_NAME} main.cpp)

FileRW/main.cpp

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include <fstream>
2+
#include <iostream>
3+
#include <limits>
4+
#include <string>
5+
6+
int main(void) {
7+
std::string opt;
8+
std::fstream *file = new std::fstream();
9+
10+
// open file in append and read mode
11+
file->open("file.txt", std::ios::app | std::ios::in);
12+
if (!file->is_open()) {
13+
std::cerr << "Unable to open file\n";
14+
15+
delete file;
16+
file = nullptr;
17+
return 0x0;
18+
}
19+
20+
do {
21+
std::cout << "Menu\n(W)rite\n(R)ead\n(Q)uit\n> ";
22+
std::getline(std::cin, opt);
23+
24+
if (opt == "w" || opt == "W") {
25+
// clear flags and set put cursor at eof
26+
file->clear();
27+
file->seekp(std::ios::end);
28+
29+
std::string data;
30+
std::cout << "Enter string: ";
31+
std::getline(std::cin, data);
32+
*file << data << std::endl;
33+
} else if (opt == "r" || opt == "R") {
34+
// clear flag and set get cursor at begining of file
35+
file->clear();
36+
file->seekg(std::ios::beg);
37+
38+
std::string data;
39+
40+
// read until hit eof and print
41+
std::getline(*file, data);
42+
while (!file->eof()) {
43+
std::cout << data << std::endl;
44+
std::getline(*file, data);
45+
}
46+
}
47+
} while (opt != "q" || opt == "Q");
48+
49+
file->close(); // close file handle
50+
51+
delete file;
52+
file = nullptr;
53+
return 0x0;
54+
}

0 commit comments

Comments
 (0)