-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_IO.h
39 lines (34 loc) · 1.41 KB
/
file_IO.h
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
// #############################################################################
// Provides useful functions for file reading and writing.
// Not yet templated as current code version only has need to output doubles.
// #############################################################################
#pragma once
#include <fstream>
#include <iomanip>
#include <limits>
namespace file_IO {
// Check whether a file exists
bool isValidFile(std::string fileName) {
if (fileName == "") return false;
std::ifstream instream(fileName);
return !(instream.fail());
}
// Read an array from file
void readArray(double *arr, std::string fileName, int n, int nIgnore=0) {
std::ifstream instream;
instream.open(fileName);
// Ignore first nIgnore lines that contain parameters
for (int i=0; i<nIgnore; i++) instream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Read in the field
for (int r=0; r<n; r++) instream >> arr[r];
instream.close();
}
// Save a host array to file
void saveArray(double *arr, std::string fileName, int n, bool append=false) {
std::ofstream outstream;
if (append) outstream.open(fileName,std::ios_base::app);
else outstream.open(fileName);
for (int r=0; r<n; r++) outstream << arr[r] << std::endl;
outstream.close();
}
}