correctly process strings with DOS-style CR-LF in lammps_commands_string()

This commit is contained in:
Axel Kohlmeyer
2021-03-13 15:48:22 -05:00
parent ec2be3f8bc
commit 5f3649ed95
2 changed files with 31 additions and 6 deletions

View File

@ -495,11 +495,15 @@ void lammps_commands_string(void *handle, const char *str)
{ {
LAMMPS *lmp = (LAMMPS *) handle; LAMMPS *lmp = (LAMMPS *) handle;
// make copy of str so can strtok() it // copy str and convert from CR-LF (DOS-style) to LF (Unix style) line
int n = strlen(str);
char *ptr, *copy = new char[n+1];
int n = strlen(str) + 1; for (ptr = copy; *str != '\0'; ++str) {
char *copy = new char[n]; if ((str[0] == '\r') && (str[1] == '\n')) continue;
strcpy(copy,str); *ptr++ = *str;
}
*ptr = '\0';
BEGIN_CAPTURE BEGIN_CAPTURE
{ {
@ -507,8 +511,9 @@ void lammps_commands_string(void *handle, const char *str)
lmp->error->all(FLERR,"Library error: issuing LAMMPS command during run"); lmp->error->all(FLERR,"Library error: issuing LAMMPS command during run");
} }
char *ptr = copy; n = strlen(copy);
for (int i=0; i < n-1; ++i) { ptr = copy;
for (int i=0; i < n; ++i) {
// handle continuation character as last character in line or string // handle continuation character as last character in line or string
if ((copy[i] == '&') && (copy[i+1] == '\n')) if ((copy[i] == '&') && (copy[i+1] == '\n'))

View File

@ -118,4 +118,24 @@ TEST_F(LibraryCommands, from_string)
lammps_commands_string(lmp, cmds.c_str()); lammps_commands_string(lmp, cmds.c_str());
if (!verbose) ::testing::internal::GetCapturedStdout(); if (!verbose) ::testing::internal::GetCapturedStdout();
EXPECT_EQ(lammps_get_natoms(lmp), 2); EXPECT_EQ(lammps_get_natoms(lmp), 2);
// repeat test with DOS/Windows style CR-LF line endings
if (!verbose) ::testing::internal::CaptureStdout();
lammps_command(lmp, "clear");
if (!verbose) ::testing::internal::GetCapturedStdout();
cmds.clear();
for (unsigned int i = 0; i < sizeof(demo_input) / sizeof(char *); ++i) {
cmds += demo_input[i];
cmds += "\r\n";
}
for (unsigned int i = 0; i < sizeof(cont_input) / sizeof(char *); ++i) {
cmds += cont_input[i];
cmds += "\r\n";
}
EXPECT_EQ(lammps_get_natoms(lmp), 0);
if (!verbose) ::testing::internal::CaptureStdout();
lammps_commands_string(lmp, cmds.c_str());
if (!verbose) ::testing::internal::GetCapturedStdout();
EXPECT_EQ(lammps_get_natoms(lmp), 2);
}; };