From: Pierre Ossman Date: Wed, 8 Sep 2021 07:02:11 +0000 (+0200) Subject: Use classic FILE I/O for storing server history X-Git-Tag: v1.11.90~4 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=478bf680c8ec3f4c07186bbc1bc23801194cc453;p=tigervnc.git Use classic FILE I/O for storing server history Error handling is more straight forward in the C file interface. --- diff --git a/vncviewer/ServerDialog.cxx b/vncviewer/ServerDialog.cxx index 9ed5c408..4fbc0811 100644 --- a/vncviewer/ServerDialog.cxx +++ b/vncviewer/ServerDialog.cxx @@ -21,6 +21,9 @@ #include #endif +#include +#include + #include #include #include @@ -31,10 +34,6 @@ #include #include -#include -#include -#include - #include #include @@ -289,22 +288,51 @@ void ServerDialog::loadServerHistory() delete[] homeDir; /* Read server history from file */ - ifstream f (filepath); - if (!f.is_open()) { - // no history file - return; + FILE* f = fopen(filepath, "r"); + if (!f) { + if (errno == ENOENT) { + // no history file + return; + } + throw Exception(_("Could not open \"%s\": %s"), + filepath, strerror(errno)); } - string line; - while(getline(f, line)) { + int lineNr = 0; + while (!feof(f)) { + char line[256]; + + // Read the next line + lineNr++; + if (!fgets(line, sizeof(line), f)) { + if (feof(f)) + break; + + fclose(f); + throw Exception(_("Failed to read line %d in file %s: %s"), + lineNr, filepath, strerror(errno)); + } + + if (strlen(line) == (sizeof(line) - 1)) { + fclose(f); + throw Exception(_("Failed to read line %d in file %s: %s"), + lineNr, filepath, _("Line too long")); + } + + int len = strlen(line); + if (line[len-1] == '\n') { + line[len-1] = '\0'; + len--; + } + if (line[len-1] == '\r') { + line[len-1] = '\0'; + len--; + } + serverHistory.push_back(line); } - if (f.bad()) { - throw Exception(_("Failed to read server history file, " - "error while reading file.")); - } - f.close(); + fclose(f); } void ServerDialog::saveServerHistory() @@ -325,20 +353,14 @@ void ServerDialog::saveServerHistory() delete[] homeDir; /* Write server history to file */ - ofstream f (filepath); - if (!f.is_open()) { - throw Exception(_("Failed to write server history file, " - "can't open file.")); - } + FILE* f = fopen(filepath, "w+"); + if (!f) + throw Exception(_("Could not open \"%s\": %s"), + filepath, strerror(errno)); // Save the last X elements to the config file. - for(size_t i=0; i < serverHistory.size() && i <= SERVER_HISTORY_SIZE; i++) { - f << serverHistory[i] << endl; - } + for(size_t i=0; i < serverHistory.size() && i <= SERVER_HISTORY_SIZE; i++) + fprintf(f, "%s\n", serverHistory[i].c_str()); - if (f.bad()) { - throw Exception(_("Failed to write server history file, " - "error while writing file.")); - } - f.close(); + fclose(f); }