Files
threaded_network_chat/log.cc

57 lines
1.2 KiB
C++

#include <sys/stat.h>
#include <fstream>
#include <ios>
#include "log.h"
#include "public.h"
// gets the number of lines in a file. returns -1 if there was an error.
int
linesInFile(string path)
{
ifstream file(path);
if (!file) {
return 1;
} else {
int lineNum = 0;
string line;
int num = 0;
while (getline(file, line))
num++;
return num;
}
}
// appends a line of text to the end of a given file. returns 0 if the file
// existed, 1 if it didn't work
int
writeToFile(string path, string line, bool incLineNum)
{
ofstream file;
struct stat s;
/*
* It APPEARS this fixes our problem where the program has to be run twice to work correctly.
*/
if (stat(path.c_str(), &s) != 0) {
file.open(path, ios_base::out);
file << "SYSTEM: No log file found. Created a new one." << endl;
file.close();
linePos += 5; /* This seems to be what actually fixes everything. Not sure. */
}
file.open(path, ios_base::app);
if (file.is_open()) {
file << line << endl;
file.close();
//linePos++ // We might also want this here at some point?
return 0;
} else {
// do something if it didn't work
return 1; // i guess that's good enough for now
}
}