-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathText.cpp
65 lines (54 loc) · 1.24 KB
/
Text.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* Reads text files
*
* Copyright (C) 2022 Marc S. Ressl
*/
#include <fstream>
#include "Text.h"
using namespace std;
/*
* Converts a string into a Text (list of lines).
*
* Parameters:
* s - String to convert
* text - Destination text
*
* Returns: success.
*/
bool getText(const string &s, Text &text)
{
text.clear();
string::size_type pos = 0;
string::size_type prev = 0;
while ((pos = s.find('\n', prev)) != string::npos)
{
text.push_back(s.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
text.push_back(s.substr(prev));
return true;
}
/*
* Reads a text file into a Text (list of lines).
*
* Parameters:
* path - Path of file to read
* text - Destination text
*
* Returns: success.
*/
bool getTextFromFile(const string path, Text &text)
{
ifstream file(path);
if (file.is_open())
{
file.seekg(0, ios::end);
int fileSize = file.tellg() > 1000000 ? 1000000 : (int)file.tellg();
string fileData(fileSize, ' ');
file.seekg(0);
file.read(&fileData[0], fileSize);
return !file.fail() && getText(fileData, text);
}
return false;
}