-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataFile.m
86 lines (72 loc) · 2.91 KB
/
DataFile.m
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
classdef DataFile < handle
%DATAFILE Helper class for data logging, intended to create CSVs
properties
data % matrix storing the data written to the file so far
fileHandle
end
properties(Constant)
% Folder for storing all data files
DEFAULT_SUBFOLDER = ['data' filesep];
DEFAULT_FILENAME = 'data.csv';
end
methods(Static)
% Creates a sensible default path and filename
% Will use a session subfolder w/ timestamp in it, by default
function path = defaultPath(sessionID)
if nargin < 1 || isempty(sessionID)
curdate30 = datestr(now, 30); % Current time in standard format: 'yyyymmddTHHMMSS' (ISO 8601)
path = [DataFile.DEFAULT_SUBFOLDER curdate30 filesep DataFile.DEFAULT_FILENAME];
else
curdate = datestr(now, 'yyyy_mm_dd');
path = [DataFile.DEFAULT_SUBFOLDER curdate filesep sessionID '.csv'];
end
end
end
methods
% Constructor: Open and prepare a new data file
function df = DataFile(path, columns)
% Check inputs
if isempty(path)
path = defaultPath();
end
if exist(path, 'file')
warning('File %s already exists! Will append to end.', path);
end
% if isempty(columns) ... throw exception?
% Initialize internal storage of data
df.data = [];
% Initialize any required folders not yet created
[folderName, ~, ~] = fileparts(path);
if ~isempty(folderName)
if ~exist(folderName, 'dir')
mkdir(folderName);
end
end
% Open file and write header line
df.fileHandle = fopen(path, 'a');
if length(columns) > 1
fprintf(df.fileHandle, '%s,', columns{1:end-1});
end
fprintf(df.fileHandle, '%s\n', columns{end});
end
% Add and save a new line of data (numeric vector)
function append(df, newData)
df.data = [df.data; newData];
% Append commas after all but the last element in the line, and
% then a newline afterwards
if length(newData) > 1
fprintf(df.fileHandle, '%f,', newData(1:end-1));
end
fprintf(df.fileHandle, '%f\n', newData(end));
end
% Destructor: close the file
% (caution: any exceptions here will silently terminate the
% function!)
function delete(df) % for deleting this handle, not the file!
fileName = fopen(df.fileHandle);
if ~isempty(fileName) % if file is still open
fclose(df.fileHandle);
end
end
end
end