Files
2025-12-05 08:54:02 +01:00

60 lines
1.4 KiB
Plaintext

// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_get_lines
#define tools_get_lines
#include <cstdlib> // malloc,free
#include <cstring> // strcpy
#include <string>
#include <vector>
namespace tools
{
inline char* str_dup(const char* a_cstr)
{
return ::strcpy((char*)::malloc(::strlen(a_cstr) + 1), a_cstr);
}
inline void str_del(char*& a_cstr)
{
if (a_cstr == NULL) return;
::free(a_cstr);
a_cstr = NULL;
}
inline void get_lines(const std::string& a_string,std::vector<std::string>& a_lines){
// a_string is a list separated by "\n" or "\\n".
// For "xxx\n\nxxx", {"xxx","","xxx"} will be created.
// WARNING : if a_string is a Windows file name, it may
// contains a \n which is not a delimiter ; like ..\data\ntuples.hbook.
a_lines.clear();
size_t length = a_string.length();
if(!length) return;
char* cstring = str_dup(a_string.c_str());
if(!cstring) return;
size_t pos = 0;
length++;
for(size_t count=0;count<length;count++) {
if( (cstring[count]=='\n') ||
(cstring[count]=='\0') ||
( (cstring[count]=='\\') && (cstring[count+1]=='n') ) ) {
char shift_one = (cstring[count]=='\n' ? 1 : 0);
cstring[count] = '\0';
a_lines.push_back(cstring+pos);
if(shift_one==1) {
pos = count+1;
} else {
pos = count+2;
count++;
}
}
}
str_del(cstring);
}
}
#endif