Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions include/rusty_iterators/file_iterator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ class FileIterator<FIterType::Buffered>
: public IterInterface<std::string, FileIterator<FIterType::Buffered>>
{
public:
explicit FileIterator(const std::string& filePath)
explicit FileIterator(const std::string& filePath, char delimiter = '\n')
{
std::ifstream is{filePath};
if (!is.is_open())
{
throw std::runtime_error{"Could not open the file."};
}
std::string nextLine;
while (std::getline(is, nextLine))
while (std::getline(is, nextLine, delimiter))
{
fileLines.push_back(std::move(nextLine));
}
Expand Down Expand Up @@ -64,7 +64,8 @@ class FileIterator<FIterType::Lazy>
: public IterInterface<std::string, FileIterator<FIterType::Lazy>>
{
public:
explicit FileIterator(const std::string& filePath) : is(filePath)
explicit FileIterator(const std::string& filePath, char delimiter = '\n')
: is(filePath), delimiter(delimiter)
{
if (!is.is_open())
{
Expand All @@ -75,7 +76,7 @@ class FileIterator<FIterType::Lazy>
auto next() -> std::optional<std::string>
{
std::string nextLine;
[[unlikely]] if (!std::getline(is, nextLine))
[[unlikely]] if (!std::getline(is, nextLine, delimiter))
{
return std::nullopt;
}
Expand All @@ -90,5 +91,6 @@ class FileIterator<FIterType::Lazy>

private:
std::ifstream is;
char delimiter;
};
} // namespace rusty_iterators::iterator
16 changes: 16 additions & 0 deletions tests/file_iterator.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ TEST(TestLazyFileIterator, TestSumIterator)
ASSERT_EQ(it.sum(), std::string{"1234"});
}

TEST(TestLazyFileIterator, TestCustomDelimiter)
{
auto testFileName = std::string{"./tests/test_delim.txt"};
auto it = FileIterator<FIterType::Lazy>{testFileName, ','};

EXPECT_THAT(it.collect(), ElementsAreArray({"1", "2", "3", "4", "5\n"}));
}

TEST(TestBufferedFileIterator, TestFileDoesNotExist)
{
auto testFileName = std::string{"./tests/abc.jpg"};
Expand Down Expand Up @@ -90,3 +98,11 @@ TEST(TestBufferedFileIterator, TestCopyBufferedIterator)
EXPECT_THAT(it.collect(), ElementsAreArray({"3", "4"}));
EXPECT_THAT(cp.collect(), ElementsAreArray({"2", "3", "4"}));
}

TEST(TestBufferedFileIterator, TestCustomDelimiter)
{
auto testFileName = std::string{"./tests/test_delim.txt"};
auto it = FileIterator<FIterType::Lazy>{testFileName, ','};

EXPECT_THAT(it.collect(), ElementsAreArray({"1", "2", "3", "4", "5\n"}));
}
1 change: 1 addition & 0 deletions tests/test_delim.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1,2,3,4,5