~vbursian/research-assistant/intervers

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
////////////////////////////////////////////////////////////////////////////////
/*! @file Files.cpp   Минимальный интерфейс файловой системы.
- This implementation uses  Qt v.4.6  -  http://qt.nokia.com/
- Part of RANet - Research Assistant Net Library (based on ANSI C++).
- Copyright(C) 2010, Viktor E. Bursian, St.Petersburg, Russia.
                     Viktor.Bursian@mail.ioffe.ru
*///////////////////////////////////////////////////////////////////////////////
#include "Files.h"
#include "Excepts.h"
//#include <unistd.h>  //for getcwd()
#include <QFileInfo>
#include <QFile>
#include <QDir>
#include <QString>
#include <QDateTime>
namespace RA {
//------------------------------------------------------------------------------

inline QString  ToQString (sString S)
{
  return QString::fromUtf8(literal(S));
}


inline sString  FromQString (QString S)
{
  return sString(literal(S.toUtf8()));
}


/*
FromQString( QFileInfo(___).absoluteFilePath() );
*/
//-------------------------------------------------------------------- sPath ---

sString  sPath::Validate (rcsString  S)
{
  return S.Translate(':','_')
          .Translate('*','_')
          .Translate('?','_')
          .Translate('"','_')
          .Translate('<','_')
          .Translate('>','_')
          .Translate('|','_')
          .Translate('\\','_');
}


sString  sPath::ValidateName (rcsString  S)
{
  return sPath::Validate(S).Translate('/','_');
}


sPath::sPath ()
{
}


sPath::sPath (rcsString  path_str)
    :ThePathStr(path_str)
{
}


//sPath::sPath (rcsString  dir
//             ,rcsString  path_relative_to_the_dir)
//{
//}


//sPath::sPath (rcsString  dir
//             ,rcsString  path_relative_to_the_dir
//             ,rcsString  extension)
//{
//}


sPath::sPath (rcsPath  a_path)
    :ThePathStr(a_path.ThePathStr)
{
}


rsPath  sPath::operator = (rcsPath  a_path)
{
  ThePathStr = a_path.ThePathStr;
  return *this;
}


sPath  sPath::Dir () const
{
  sString  dir;
  sString  name;
  sString  extension;
  Split(dir,name,extension);
  return sPath(dir);
}


sString  sPath::Name () const
{
  sString  dir;
  sString  name;
  sString  extension;
  Split(dir,name,extension);
  return name;
}


sString  sPath::Ext () const
{
  sString  dir;
  sString  name;
  sString  extension;
  Split(dir,name,extension);
  return extension;
}


void  sPath::Validate ()
{
  ThePathStr=Validate(ThePathStr);
}


sPath  sPath::CurrentDir ()
{
  sString                     D;
  D=FromQString( QDir::currentPath() );
  return D;
}


bool  sPath::Exists () const
{
  return QFileInfo( ToQString(ThePathStr) ).exists();
}


sTime  sPath::ModificationTime () const
{
  return sTime::FromMillisecondsSinceEpoch(
        QFileInfo( ToQString(ThePathStr) ).lastModified().toMSecsSinceEpoch()
                                          );
}


sTime  sPath::AccessTime () const
{
  return sTime::FromMillisecondsSinceEpoch(
        QFileInfo( ToQString(ThePathStr) ).lastRead().toMSecsSinceEpoch()
                                          );
}


sTime  sPath::CreationTime () const
{
  return sTime::FromMillisecondsSinceEpoch(
        QFileInfo( ToQString(ThePathStr) ).created().toMSecsSinceEpoch()
                                          );
}


bool  sPath::Erase () const
{
  bool                        OK = false;
  OK = QFile::remove( ToQString(ThePathStr) );
  /*! @todo{env} remove empty dirs */
  return OK;
}

//     <cstdio>
//
//int remove ( const char * filename );
//  int i;
//  if (system(NULL)) cout<<"Ok  ";
//    else exit (1);
//  cout << "Executing command mkdir..." << endl;
//  i=system ("mkdir -p ratemp/radata");
//  cout << "The value returned was:" << i << endl;



bool  sPath::CreateDirForIt () const
{
  QDir                        CD(QDir::current());
  bool                        OK = false;
  OK = CD.mkpath( ToQString(Dir().PathStr()) );
  return OK;
}


void  sPath::Split (rsString  dir
                   ,rsString  name
                   ,rsString  extension) const
{
  sString                     tail(ThePathStr);
  size_t                      i=tail.Pos("/");
  while( i < tail.Length() ){
    dir+=tail.Substr(0,i+1);
    tail=tail.Tail(i+1);
    i=tail.Pos("/");
  }
  if( dir.Length() > 1 ){
    dir=dir.Substr(0,dir.Length()-1);
  }
  if( ! tail.Empty() ){
    i=tail.Pos(".");
    while( i < tail.Length() ){
      name+=tail.Substr(0,i+1);
      tail=tail.Tail(i+1);
      i=tail.Pos(".");
    }
    if( name.Length() <= 1 ){
      name+=tail;
    }else{
      name=name.Substr(0,name.Length()-1);
      extension=tail;
    }
  }
}

//-------------------------------------------------------------------- sFile ---

sFile::~sFile()
{
  if( State==Opened ){
    Close();
  }
}


void  sFile::Assign(rcsString fname, eTypeMode type)
{
  if( State == Opened ){
    Close();
    throw xProgramError("sFile::Assign - it is open"
                       ,__FILE__,__LINE__);
  }
  FullName=fname;
  Type=type;
  if( FullName.Empty()  ){
    State=NotAssigned;
  }else{
    State=Closed;
  }
}


void  sFile::Assign(rcsPath   file_path, eTypeMode type)
{
  if( State == Opened ){
    Close();
    throw xProgramError("sFile::Assign - it is open"
                       ,__FILE__,__LINE__);
  }
  FullName=file_path.PathStr();
  Type=type;
  if( FullName.Empty()  ){
    State=NotAssigned;
  }else{
    State=Closed;
  }
}

/*
FILE * fopen ( const char * filename, const char * mode );

Open file
Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE object whose pointer is returned. The operations that are allowed on the stream and how these are performed are defined by the mode parameter.
The running environment supports at least FOPEN_MAX files open simultaneously; FOPEN_MAX is a macro constant defined in <cstdio>.

Parameters

filename
    C string containing the name of the file to be opened. This paramenter must follow the file name specifications of the running environment and can include a path if the system supports it.
mode
    C string containing a file access modes. It can be:
    "r"	Open a file for reading. The file must exist.
    "w"	Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
    "a"	Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.
    "r+"	Open a file for update both reading and writing. The file must exist.
    "w+"	Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
    "a+"	Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.


With the mode specifiers above the file is open as a text file. In order to open a file as a binary file, a "b" character has to be included in the mode string. This additional "b" character can either be appended at the end of the string (thus making the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+").
Additional characters may follow the sequence, although they should have no effect. For example, "t" is sometimes appended to make explicit the file is a text file.
In the case of text files, depending on the environment where the application runs, some special character conversion may occur in input/output operations to adapt them to a system-specific text file format. In many environments, such as most UNIX-based systems, it makes no difference to open a file as a text file or a binary file; Both are treated exactly the same way, but differentiation is recommended for a better portability.
For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.
------------------------------------
void fstream::open ( const char * filename,
            ios_base::openmode mode = ios_base::in | ios_base::out );

Open file
Opens a file whose name is s, associating its content with the stream object to perform input/output operations on it. The operations allowed and some operating details depend on parameter mode.

The function effectively calls rdbuf()->open(filename,mode).

If the object already has a file associated (open), the function fails.

On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.

Parameters

filename
    C-string containing the name of the file to be opened.
mode
    Flags describing the requested i/o mode for the file. This is an object of type ios_base::openmode, which consists on a combination of one or more of the following flags defined as member constants:
    flag value	opening mode
    app	(append) Set the stream's position indicator to the end of the stream before each output operation.
    ate	(at end) Set the stream's position indicator to the end of the stream on opening.
    binary	(binary) Consider stream as binary rather than text.
    in	(input) Allow input operations on the stream.
    out	(output) Allow output operations on the stream.
    trunc	(truncate) Any current content is discarded, assuming a length of zero on opening.



*/

void  sFile::Open(eOpenMode mode)
{
  if( State == NotAssigned ){
    throw xProgramError("Opening an sFile before it is assigned"
                       ,__FILE__,__LINE__);
  }else if( State == Opened ){
    throw xProgramError("already opened"
                       ,__FILE__,__LINE__);  //"File \"",FullName,"\" already opened"
  }else{
    std::ios_base::openmode          flags;
    switch (mode) {
      case Reading:
              flags= std::ios_base::in;
              break;
      case Writing:
              flags= std::ios_base::out | std::ios_base::trunc;
              break;
      case Updating:
              flags= std::ios_base::in | std::ios_base::out;
              break;
      case Appending:
              flags= std::ios_base::out | std::ios_base::app;
              break;
      default:
              throw xProgramError("",__FILE__,__LINE__);
    };
    if( Type == Binary ){
      flags= flags | std::ios_base::binary;
    };
    open((literal)(QFile::encodeName(ToQString(FullName))),flags);
    if( is_open() ){
      State=Opened;
      Mode=mode;
    }else{
      Mode=mode;//DUMMY FOR DEBUG
      //! @todo{env}      throw xError();
    }
  }
}


void  sFile::Close()
{
  if( State == NotAssigned ){
    throw xProgramError("Closing an sFile before it is assigned"
                       ,__FILE__,__LINE__);
  }else if( State==Closed ){
  }else{
    close();
    State=Closed;
  }
}


//bool  sFile::TryToOpen (eOpenMode mode)
//{
//  try{
//    Open(mode);
//    return true;
//  }catch(...){
//    return false;
//  };
//};
//
//
//bool  sFile::TryToClose ()
//{
//  try{
//    Close();
//    return true;
//  }catch(...){
//    return false;
//  };
//};


//------------------------------------------------------------------------------
} //namespace RA