Coverage Report

Created: 2026-11-12 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/netcdf-c/libdispatch/dfile.c
Line
Count
Source
1
/**
2
 * @file
3
 *
4
 * File create and open functions
5
 *
6
 * These functions end up calling functions in one of the dispatch
7
 * layers (netCDF-4, dap server, etc).
8
 *
9
 * Copyright 2018 University Corporation for Atmospheric
10
 * Research/Unidata. See COPYRIGHT file for more info.
11
 */
12
13
#include "config.h"
14
#include <stdlib.h>
15
#ifdef HAVE_STRING_H
16
#include <string.h>
17
#endif
18
#ifdef HAVE_SYS_RESOURCE_H
19
#include <sys/resource.h>
20
#endif
21
#ifdef HAVE_SYS_TYPES_H
22
#include <sys/types.h>
23
#endif
24
#ifdef HAVE_SYS_STAT_H
25
#include <sys/stat.h>
26
#endif
27
28
#ifdef HAVE_UNISTD_H
29
#include <unistd.h> /* lseek() */
30
#endif
31
32
#ifdef HAVE_STDIO_H
33
#include <stdio.h>
34
#endif
35
36
#include "ncdispatch.h"
37
#include "netcdf_mem.h"
38
#include "ncpathmgr.h"
39
#include "fbits.h"
40
41
#undef DEBUG
42
43
#ifndef nulldup
44
 #define nulldup(s) ((s)?strdup(s):NULL)
45
#endif
46
47
48
/* User-defined formats - 64 slots.
49
 * These arrays store dispatch tables and magic numbers for up to 64 custom formats.
50
 * Array-based design replaces the previous individual UDF0/UDF1 global variables. */
51
NC_Dispatch *UDF_dispatch_tables[NC_MAX_UDF_FORMATS] = {NULL};
52
char UDF_magic_numbers[NC_MAX_UDF_FORMATS][NC_MAX_MAGIC_NUMBER_LEN + 1] = {{0}};
53
54
/** Helper function to convert a UDF mode flag to array index (0-63).
55
 * A UDF mode is marked by NC_UDF_FLAG; the slot number is held in a
56
 * 6-bit field at NC_UDF_NUM_SHIFT. Build UDF modes with NC_UDF(n).
57
 * @param mode_flag The mode flag, e.g. NC_UDF(3)
58
 * @return Array index 0-63, or -1 if NC_UDF_FLAG is not set or the
59
 * mode has bits set above the slot number field (as produced by
60
 * NC_UDF(n) with n outside 0-63) */
61
0
static int udf_mode_to_index(int mode_flag) {
62
0
    if (!fIsSet(mode_flag, NC_UDF_FLAG))
63
0
        return -1;
64
    /* Reject modes with bits set above the slot number field. These
65
     * result from NC_UDF(n) with n outside 0-63 and must not be
66
     * silently aliased to a valid slot. */
67
0
    if (mode_flag & ~((1 << (NC_UDF_NUM_SHIFT + 6)) - 1))
68
0
        return -1;
69
0
    return (mode_flag >> NC_UDF_NUM_SHIFT) & NC_UDF_NUM_MASK;
70
0
}
71
72
/** Helper function to convert NC_FORMATX_UDF(n) to array index (0-63).
73
 * @param formatx The format constant (NC_FORMATX_UDF(0) through NC_FORMATX_UDF(63))
74
 * @return Array index 0-63, or -1 if not a valid UDF format constant
75
 * @note Handles the gap in format numbering: UDF0=8, UDF1=9, UDF2=11, UDF3=12, etc.
76
 *       (NC_FORMATX_NCZARR=10 occupies the slot between UDF1 and UDF2) */
77
70
static int udf_formatx_to_index(int formatx) {
78
    /* UDF0 and UDF1 are sequential (8, 9) */
79
70
    if (formatx >= NC_FORMATX_UDF0 && formatx <= NC_FORMATX_UDF1)
80
0
        return formatx - NC_FORMATX_UDF0;
81
    /* UDF2-UDF63 start at 11 (skipping NCZARR at 10) */
82
70
    if (formatx >= NC_FORMATX_UDF2 && formatx <= NC_FORMATX_UDF_MAX)
83
0
        return formatx - NC_FORMATX_UDF2 + 2;
84
70
    return -1;
85
70
}
86
87
/**************************************************/
88
89
90
/** \defgroup datasets NetCDF File and Data I/O
91
92
    NetCDF opens datasets as files or remote access URLs.
93
94
    A netCDF dataset that has not yet been opened can only be referred to
95
    by its dataset name. Once a netCDF dataset is opened, it is referred
96
    to by a netCDF ID, which is a small non-negative integer returned when
97
    you create or open the dataset. A netCDF ID is much like a file
98
    descriptor in C or a logical unit number in FORTRAN. In any single
99
    program, the netCDF IDs of distinct open netCDF datasets are
100
    distinct. A single netCDF dataset may be opened multiple times and
101
    will then have multiple distinct netCDF IDs; however at most one of
102
    the open instances of a single netCDF dataset should permit
103
    writing. When an open netCDF dataset is closed, the ID is no longer
104
    associated with a netCDF dataset.
105
106
    Functions that deal with the netCDF library include:
107
    - Get version of library.
108
    - Get error message corresponding to a returned error code.
109
110
    The operations supported on a netCDF dataset as a single object are:
111
    - Create, given dataset name and whether to overwrite or not.
112
    - Open for access, given dataset name and read or write intent.
113
    - Put into define mode, to add dimensions, variables, or attributes.
114
    - Take out of define mode, checking consistency of additions.
115
    - Close, writing to disk if required.
116
    - Inquire about the number of dimensions, number of variables,
117
    number of global attributes, and ID of the unlimited dimension, if
118
    any.
119
    - Synchronize to disk to make sure it is current.
120
    - Set and unset nofill mode for optimized sequential writes.
121
    - After a summary of conventions used in describing the netCDF
122
    interfaces, the rest of this chapter presents a detailed description
123
    of the interfaces for these operations.
124
*/
125
126
/**
127
 * Add handling of user-defined format.
128
 *
129
 * User-defined formats allow users to write a library which can read
130
 * their own proprietary format as if it were netCDF. This allows
131
 * existing netCDF codes to work on non-netCDF data formats.
132
 *
133
 * User-defined formats work by specifying a netCDF dispatch
134
 * table. The dispatch table is a struct of (mostly) C function
135
 * pointers. It contains pointers to the key functions of the netCDF
136
 * API. Once these functions are provided, and the dispatch table is
137
 * specified, the netcdf-c library can read any format.
138
 *
139
 * @note Unlike the public netCDF API, the dispatch table may not be
140
 * backward compatible between netCDF releases. Instead, it contains a
141
 * dispatch version number. If this number is not correct (i.e. does
142
 * not match the current dispatch table version), then ::NC_EINVAL
143
 * will be returned.
144
 *
145
 * @param mode_flag NC_UDF(n) for slot n (0-63).
146
 * @param dispatch_table Pointer to dispatch table to use for this user format.
147
 * @param magic_number Magic number used to identify file. Ignored if
148
 * NULL.
149
 *
150
 * @return ::NC_NOERR No error.
151
 * @return ::NC_EINVAL Invalid input.
152
 * @author Ed Hartnett
153
 * @ingroup datasets
154
 */
155
int
156
nc_def_user_format(int mode_flag, NC_Dispatch *dispatch_table, char *magic_number)
157
0
{
158
0
    int udf_index;
159
160
    /* Check inputs. */
161
0
    if (!dispatch_table)
162
0
        return NC_EINVAL;
163
0
    if (magic_number && strlen(magic_number) > NC_MAX_MAGIC_NUMBER_LEN)
164
0
        return NC_EINVAL;
165
166
    /* Check the version of the dispatch table provided. */
167
0
    if (dispatch_table->dispatch_version != NC_DISPATCH_VERSION)
168
0
        return NC_EINVAL;
169
    /* user defined magic numbers not allowed with netcdf3 modes */ 
170
0
    if (magic_number && (fIsSet(mode_flag, NC_64BIT_OFFSET) ||
171
0
                         fIsSet(mode_flag, NC_64BIT_DATA) ||
172
0
                        (fIsSet(mode_flag, NC_CLASSIC_MODEL) &&
173
0
                        !fIsSet(mode_flag, NC_NETCDF4))))
174
0
        return NC_EINVAL;
175
176
    /* Get the UDF index from the mode flag. */
177
0
    udf_index = udf_mode_to_index(mode_flag);
178
0
    if (udf_index < 0 || udf_index >= NC_MAX_UDF_FORMATS)
179
0
        return NC_EINVAL;
180
181
    /* Retain a pointer to the dispatch_table and a copy of the magic
182
     * number, if one was provided. */
183
0
    UDF_dispatch_tables[udf_index] = dispatch_table;
184
0
    if (magic_number) {
185
0
        strncpy(UDF_magic_numbers[udf_index], magic_number, NC_MAX_MAGIC_NUMBER_LEN);
186
        /* Ensure null-termination since strncpy doesn't guarantee it if source >= max length */
187
0
        UDF_magic_numbers[udf_index][NC_MAX_MAGIC_NUMBER_LEN] = '\0';
188
0
    }
189
190
0
    return NC_NOERR;
191
0
}
192
193
/**
194
 * Inquire about user-defined format.
195
 *
196
 * @param mode_flag NC_UDF(n) for slot n (0-63).
197
 * 
198
 * @param dispatch_table Pointer that gets pointer to dispatch table to use for this user format, or NULL if this user-defined format is not defined. Ignored if NULL.
199
 * @param magic_number Pointer that gets magic number used to identify file, if one has been set. Magic number will be of max size NC_MAX_MAGIC_NUMBER_LEN. Ignored if NULL.
200
 * @returns ::NC_NOERR No error.
201
 * @returns ::NC_EINVAL Invalid input.
202
 * @author Ed Hartnett
203
 * @ingroup datasets
204
 */
205
int
206
nc_inq_user_format(int mode_flag, NC_Dispatch **dispatch_table, char *magic_number)
207
0
{
208
0
    int udf_index;
209
210
    /* Get the UDF index from the mode flag. */
211
0
    udf_index = udf_mode_to_index(mode_flag);
212
0
    if (udf_index < 0 || udf_index >= NC_MAX_UDF_FORMATS)
213
0
        return NC_EINVAL;
214
215
    /* Return the dispatch table and magic number. */
216
0
    if (dispatch_table)
217
0
        *dispatch_table = UDF_dispatch_tables[udf_index];
218
0
    if (magic_number)
219
0
        strncpy(magic_number, UDF_magic_numbers[udf_index], NC_MAX_MAGIC_NUMBER_LEN);
220
221
0
    return NC_NOERR;
222
0
}
223
224
/**  \ingroup datasets
225
     Create a new netCDF file.
226
227
     This function creates a new netCDF dataset, returning a netCDF ID that
228
     can subsequently be used to refer to the netCDF dataset in other
229
     netCDF function calls. The new netCDF dataset opened for write access
230
     and placed in define mode, ready for you to add dimensions, variables,
231
     and attributes.
232
233
     \param path The file name of the new netCDF dataset.
234
235
     \param cmode The creation mode flag. The following flags are available:
236
     NC_CLOBBER (overwrite existing file),
237
     NC_NOCLOBBER (do not overwrite existing file),
238
     NC_SHARE (limit write caching - netcdf classic files only),
239
     NC_64BIT_OFFSET (create 64-bit offset file),
240
     NC_64BIT_DATA (alias NC_CDF5) (create CDF-5 file),
241
     NC_NETCDF4 (create netCDF-4/HDF5 file),
242
     NC_CLASSIC_MODEL (enforce netCDF classic mode on netCDF-4/HDF5 files),
243
     NC_DISKLESS (store data in memory), and
244
     NC_PERSIST (force the NC_DISKLESS data from memory to a file),
245
     NC_MMAP (use MMAP for NC_DISKLESS instead of NC_INMEMORY -- deprecated).
246
     See discussion below.
247
248
     \param ncidp Pointer to location where returned netCDF ID is to be
249
     stored.
250
251
     <h2>The cmode Flag</h2>
252
253
     The cmode flag is used to control the type of file created, and some
254
     aspects of how it may be used.
255
256
     Setting NC_NOCLOBBER means you do not want to clobber (overwrite) an
257
     existing dataset; an error (NC_EEXIST) is returned if the specified
258
     dataset already exists.
259
260
     The NC_SHARE flag is appropriate when one process may be writing the
261
     dataset and one or more other processes reading the dataset
262
     concurrently; it means that dataset accesses are not buffered and
263
     caching is limited. Since the buffering scheme is optimized for
264
     sequential access, programs that do not access data sequentially may
265
     see some performance improvement by setting the NC_SHARE flag. This
266
     flag is ignored for netCDF-4 files.
267
268
     Setting NC_64BIT_OFFSET causes netCDF to create a 64-bit offset format
269
     file, instead of a netCDF classic format file. The 64-bit offset
270
     format imposes far fewer restrictions on very large (i.e. over 2 GB)
271
     data files. See Large File Support.
272
273
     Setting NC_64BIT_DATA (alias NC_CDF5) causes netCDF to create a CDF-5
274
     file format that supports large files (i.e. over 2GB) and large
275
     variables (over 2B array elements.). See Large File Support.
276
277
     A zero value (defined for convenience as NC_CLOBBER) specifies the
278
     default behavior: overwrite any existing dataset with the same file
279
     name and buffer and cache accesses for efficiency. The dataset will be
280
     in netCDF classic format. See NetCDF Classic Format Limitations.
281
282
     Setting NC_NETCDF4 causes netCDF to create a HDF5/NetCDF-4 file.
283
284
     Setting NC_CLASSIC_MODEL causes netCDF to enforce the classic data
285
     model in this file. (This only has effect for netCDF-4/HDF5 files, as
286
     CDF-1, 2 and 5 files always use the classic model.) When
287
     used with NC_NETCDF4, this flag ensures that the resulting
288
     netCDF-4/HDF5 file may never contain any new constructs from the
289
     enhanced data model. That is, it cannot contain groups, user defined
290
     types, multiple unlimited dimensions, or new atomic types. The
291
     advantage of this restriction is that such files are guaranteed to
292
     work with existing netCDF software.
293
294
     Setting NC_DISKLESS causes netCDF to create the file only in
295
     memory and to optionally write the final contents to the
296
     correspondingly named disk file. This allows for the use of
297
     files that have no long term purpose. Operating on an existing file
298
     in memory may also be faster. The decision on whether
299
     or not to "persist" the memory contents to a disk file is
300
     described in detail in the file docs/inmemory.md, which is
301
     definitive.  By default, closing a diskless fill will cause it's
302
     contents to be lost.
303
304
     If NC_DISKLESS is going to be used for creating a large classic
305
     file, it behooves one to use nc__create and specify an
306
     appropriately large value of the initialsz parameter to avoid to
307
     many extensions to the in-memory space for the file.  This flag
308
     applies to files in classic format and to file in extended
309
     format (netcdf-4).
310
311
     Note that nc_create(path,cmode,ncidp) is equivalent to the invocation of
312
     nc__create(path,cmode,NC_SIZEHINT_DEFAULT,NULL,ncidp).
313
314
     \returns ::NC_NOERR No error.
315
     \returns ::NC_EEXIST Specifying a file name of a file that exists and also specifying NC_NOCLOBBER.
316
     \returns ::NC_EPERM Attempting to create a netCDF file in a directory where you do not have permission to create files.
317
     \returns ::NC_ENOMEM System out of memory.
318
     \returns ::NC_ENFILE Too many files open.
319
     \returns ::NC_EHDFERR HDF5 error (netCDF-4 files only).
320
     \returns ::NC_EFILEMETA Error writing netCDF-4 file-level metadata in
321
     HDF5 file. (netCDF-4 files only).
322
     \returns ::NC_EDISKLESS if there was an error in creating the
323
     in-memory file.
324
325
     \note When creating a netCDF-4 file HDF5 error reporting is turned
326
     off, if it is on. This doesn't stop the HDF5 error stack from
327
     recording the errors, it simply stops their display to the user
328
     through stderr.
329
330
     <h1>Examples</h1>
331
332
     In this example we create a netCDF dataset named foo.nc; we want the
333
     dataset to be created in the current directory only if a dataset with
334
     that name does not already exist:
335
336
     @code
337
     #include <netcdf.h>
338
     ...
339
     int status = NC_NOERR;
340
     int ncid;
341
     ...
342
     status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
343
     if (status != NC_NOERR) handle_error(status);
344
     @endcode
345
346
     In this example we create a netCDF dataset named foo_large.nc. It will
347
     be in the 64-bit offset format.
348
349
     @code
350
     #include <netcdf.h>
351
     ...
352
     int status = NC_NOERR;
353
     int ncid;
354
     ...
355
     status = nc_create("foo_large.nc", NC_NOCLOBBER|NC_64BIT_OFFSET, &ncid);
356
     if (status != NC_NOERR) handle_error(status);
357
     @endcode
358
359
     In this example we create a netCDF dataset named foo_HDF5.nc. It will
360
     be in the HDF5 format.
361
362
     @code
363
     #include <netcdf.h>
364
     ...
365
     int status = NC_NOERR;
366
     int ncid;
367
     ...
368
     status = nc_create("foo_HDF5.nc", NC_NOCLOBBER|NC_NETCDF4, &ncid);
369
     if (status != NC_NOERR) handle_error(status);
370
     @endcode
371
372
     In this example we create a netCDF dataset named
373
     foo_HDF5_classic.nc. It will be in the HDF5 format, but will not allow
374
     the use of any netCDF-4 advanced features. That is, it will conform to
375
     the classic netCDF-3 data model.
376
377
     @code
378
     #include <netcdf.h>
379
     ...
380
     int status = NC_NOERR;
381
     int ncid;
382
     ...
383
     status = nc_create("foo_HDF5_classic.nc", NC_NOCLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL, &ncid);
384
     if (status != NC_NOERR) handle_error(status);
385
     @endcode
386
387
     In this example we create an in-memory netCDF classic dataset named
388
     diskless.nc whose content will be lost when nc_close() is called.
389
390
     @code
391
     #include <netcdf.h>
392
     ...
393
     int status = NC_NOERR;
394
     int ncid;
395
     ...
396
     status = nc_create("diskless.nc", NC_DISKLESS, &ncid);
397
     if (status != NC_NOERR) handle_error(status);
398
     @endcode
399
400
     In this example we create a in-memory netCDF classic dataset named
401
     diskless.nc and specify that it should be made persistent
402
     in a file named diskless.nc when nc_close() is called.
403
404
     @code
405
     #include <netcdf.h>
406
     ...
407
     int status = NC_NOERR;
408
     int ncid;
409
     ...
410
     status = nc_create("diskless.nc", NC_DISKLESS|NC_PERSIST, &ncid);
411
     if (status != NC_NOERR) handle_error(status);
412
     @endcode
413
414
     A variant of nc_create(), nc__create() (note the double underscore) allows
415
     users to specify two tuning parameters for the file that it is
416
     creating.  */
417
int
418
nc_create(const char *path, int cmode, int *ncidp)
419
0
{
420
0
    return nc__create(path,cmode,NC_SIZEHINT_DEFAULT,NULL,ncidp);
421
0
}
422
423
/**
424
 * Create a netCDF file with some extra parameters controlling classic
425
 * file caching.
426
 *
427
 * Like nc_create(), this function creates a netCDF file.
428
 *
429
 * @param path The file name of the new netCDF dataset.
430
 * @param cmode The creation mode flag, the same as in nc_create().
431
 * @param initialsz On some systems, and with custom I/O layers, it
432
 * may be advantageous to set the size of the output file at creation
433
 * time. This parameter sets the initial size of the file at creation
434
 * time. This only applies to classic CDF-1, 2, and 5 files.  The
435
 * special value NC_SIZEHINT_DEFAULT (which is the value 0), lets the
436
 * netcdf library choose a suitable initial size.
437
 * @param chunksizehintp A pointer to the chunk size hint, which
438
 * controls a space versus time tradeoff, memory allocated in the
439
 * netcdf library versus number of system calls. Because of internal
440
 * requirements, the value may not be set to exactly the value
441
 * requested. The actual value chosen is returned by reference. Using
442
 * a NULL pointer or having the pointer point to the value
443
 * NC_SIZEHINT_DEFAULT causes the library to choose a default. How the
444
 * system chooses the default depends on the system. On many systems,
445
 * the "preferred I/O block size" is available from the stat() system
446
 * call, struct stat member st_blksize. If this is available it is
447
 * used. Lacking that, twice the system pagesize is used. Lacking a
448
 * call to discover the system pagesize, we just set default bufrsize
449
 * to 8192. The bufrsize is a property of a given open netcdf
450
 * descriptor ncid, it is not a persistent property of the netcdf
451
 * dataset. This only applies to classic files.
452
 * @param ncidp Pointer to location where returned netCDF ID is to be
453
 * stored.
454
 *
455
 * @note This function uses the same return codes as the nc_create()
456
 * function.
457
 *
458
 * @returns ::NC_NOERR No error.
459
 * @returns ::NC_ENOMEM System out of memory.
460
 * @returns ::NC_EHDFERR HDF5 error (netCDF-4 files only).
461
 * @returns ::NC_EFILEMETA Error writing netCDF-4 file-level metadata in
462
 * HDF5 file. (netCDF-4 files only).
463
 * @returns ::NC_EDISKLESS if there was an error in creating the
464
 * in-memory file.
465
 *
466
 * <h1>Examples</h1>
467
 *
468
 * In this example we create a netCDF dataset named foo_large.nc; we
469
 * want the dataset to be created in the current directory only if a
470
 * dataset with that name does not already exist. We also specify that
471
 * bufrsize and initial size for the file.
472
 *
473
 * @code
474
 #include <netcdf.h>
475
 ...
476
 int status = NC_NOERR;
477
 int ncid;
478
 int intialsz = 2048;
479
 int *bufrsize;
480
 ...
481
 *bufrsize = 1024;
482
 status = nc__create("foo.nc", NC_NOCLOBBER, initialsz, bufrsize, &ncid);
483
 if (status != NC_NOERR) handle_error(status);
484
 @endcode
485
 *
486
 * @ingroup datasets
487
 * @author Glenn Davis
488
 */
489
int
490
nc__create(const char *path, int cmode, size_t initialsz,
491
           size_t *chunksizehintp, int *ncidp)
492
0
{
493
0
    return NC_create(path, cmode, initialsz, 0,
494
0
                     chunksizehintp, 0, NULL, ncidp);
495
0
}
496
497
/** \ingroup datasets
498
    Create a netCDF file with the contents stored in memory.
499
500
    \param path Must be non-null, but otherwise only used to set the dataset name.
501
502
    \param mode the mode flags; Note that this procedure uses a limited set of flags because it forcibly sets NC_INMEMORY.
503
504
    \param initialsize (advisory) size to allocate for the created file
505
506
    \param ncidp Pointer to location where returned netCDF ID is to be
507
    stored.
508
509
    \returns ::NC_NOERR No error.
510
511
    \returns ::NC_ENOMEM Out of memory.
512
513
    \returns ::NC_EDISKLESS diskless io is not enabled for fails.
514
515
    \returns ::NC_EINVAL, etc. other errors also returned by nc_open.
516
517
    <h1>Examples</h1>
518
519
    In this example we use nc_create_mem() to create a classic netCDF dataset
520
    named foo.nc. The initial size is set to 4096.
521
522
    @code
523
    #include <netcdf.h>
524
    ...
525
    int status = NC_NOERR;
526
    int ncid;
527
    int mode = 0;
528
    size_t initialsize = 4096;
529
    ...
530
    status = nc_create_mem("foo.nc", mode, initialsize, &ncid);
531
    if (status != NC_NOERR) handle_error(status);
532
    @endcode
533
*/
534
535
int
536
nc_create_mem(const char* path, int mode, size_t initialsize, int* ncidp)
537
0
{
538
0
    if(mode & NC_MMAP) return NC_EINVAL;
539
0
    mode |= NC_INMEMORY; /* Specifically, do not set NC_DISKLESS */
540
0
    return NC_create(path, mode, initialsize, 0, NULL, 0, NULL, ncidp);
541
0
}
542
543
/**
544
 * @internal Create a file with special (deprecated) Cray settings.
545
 *
546
 * @deprecated This function was used in the old days with the Cray at
547
 * NCAR. The Cray is long gone, and this call is supported only for
548
 * backward compatibility. Use nc_create() instead.
549
 *
550
 * @param path File name.
551
 * @param cmode Create mode.
552
 * @param initialsz Initial size of metadata region for classic files,
553
 * ignored for other files.
554
 * @param basepe Deprecated parameter from the Cray days.
555
 * @param chunksizehintp A pointer to the chunk size hint. This only
556
 * applies to classic files.
557
 * @param ncidp Pointer that gets ncid.
558
 *
559
 * @return ::NC_NOERR No error.
560
 * @author Glenn Davis
561
 */
562
int
563
nc__create_mp(const char *path, int cmode, size_t initialsz,
564
              int basepe, size_t *chunksizehintp, int *ncidp)
565
0
{
566
0
    return NC_create(path, cmode, initialsz, basepe,
567
0
                     chunksizehintp, 0, NULL, ncidp);
568
0
}
569
570
/**
571
 * Open an existing netCDF file.
572
 *
573
 * This function opens an existing netCDF dataset for access. It
574
 * determines the underlying file format automatically. Use the same
575
 * call to open a netCDF classic or netCDF-4 file.
576
 *
577
 * @param path File name for netCDF dataset to be opened. When the dataset
578
 * is located on some remote server, then the path may be an OPeNDAP URL
579
 * rather than a file path.
580
 * @param omode The open mode flag may include NC_WRITE (for read/write
581
 * access) and NC_SHARE (see below) and NC_DISKLESS (see below).
582
 * @param ncidp Pointer to location where returned netCDF ID is to be
583
 * stored.
584
 *
585
 * <h2>Open Mode</h2>
586
 *
587
 * A zero value (or ::NC_NOWRITE) specifies the default behavior: open
588
 * the dataset with read-only access, buffering and caching accesses
589
 * for efficiency.
590
 *
591
 * Otherwise, the open mode is ::NC_WRITE, ::NC_SHARE, or
592
 * ::NC_WRITE|::NC_SHARE. Setting the ::NC_WRITE flag opens the
593
 * dataset with read-write access. ("Writing" means any kind of change
594
 * to the dataset, including appending or changing data, adding or
595
 * renaming dimensions, variables, and attributes, or deleting
596
 * attributes.)
597
 *
598
 * The NC_SHARE flag is only used for netCDF classic
599
 * files. It is appropriate when one process may be writing the
600
 * dataset and one or more other processes reading the dataset
601
 * concurrently; it means that dataset accesses are not buffered and
602
 * caching is limited. Since the buffering scheme is optimized for
603
 * sequential access, programs that do not access data sequentially
604
 * may see some performance improvement by setting the NC_SHARE flag.
605
 *
606
 * This procedure may also be invoked with the NC_DISKLESS flag set in
607
 * the omode argument if the file to be opened is a classic format
608
 * file.  For nc_open(), this flag applies only to files in classic
609
 * format.  If the file is of type NC_NETCDF4, then the NC_DISKLESS
610
 * flag will be ignored.
611
 *
612
 * If NC_DISKLESS is specified, then the whole file is read completely
613
 * into memory. In effect this creates an in-memory cache of the file.
614
 * If the omode flag also specifies NC_PERSIST, then the in-memory cache
615
 * will be re-written to the disk file when nc_close() is called.  For
616
 * some kinds of manipulations, having the in-memory cache can speed
617
 * up file processing. But in simple cases, non-cached processing may
618
 * actually be faster than using cached processing.  You will need to
619
 * experiment to determine if the in-memory caching is worthwhile for
620
 * your application.
621
 *
622
 * Normally, NC_DISKLESS allocates space in the heap for storing the
623
 * in-memory file. If, however, the ./configure flags --enable-mmap is
624
 * used, and the additional omode flag NC_MMAP is specified, then the
625
 * file will be opened using the operating system MMAP facility.  This
626
 * flag only applies to files in classic format. Extended format
627
 * (netcdf-4) files will ignore the NC_MMAP flag.
628
 *
629
 * In most cases, using MMAP provides no advantage for just
630
 * NC_DISKLESS. The one case where using MMAP is an advantage is when
631
 * a file is to be opened and only a small portion of its data is to
632
 * be read and/or written.  In this scenario, MMAP will cause only the
633
 * accessed data to be retrieved from disk. Without MMAP, NC_DISKLESS
634
 * will read the whole file into memory on nc_open. Thus, MMAP will
635
 * provide some performance improvement in this case.
636
 *
637
 * It is not necessary to pass any information about the format of the
638
 * file being opened. The file type will be detected automatically by
639
 * the netCDF library.
640
 *
641
 * If a the path is a DAP URL, then the open mode is read-only.
642
 * Setting NC_WRITE will be ignored.
643
 *
644
 * As of version 4.3.1.2, multiple calls to nc_open with the same
645
 * path will return the same ncid value.
646
 *
647
 * @note When opening a netCDF-4 file HDF5 error reporting is turned
648
 * off, if it is on. This doesn't stop the HDF5 error stack from
649
 * recording the errors, it simply stops their display to the user
650
 * through stderr.
651
 *
652
 * nc_open()returns the value NC_NOERR if no errors
653
 * occurred. Otherwise, the returned status indicates an
654
 * error. Possible causes of errors include:
655
 *
656
 * Note that nc_open(path,omode,ncidp) is equivalent to the invocation
657
 * of nc__open(path,omode,NC_SIZEHINT_DEFAULT,NULL,ncidp).
658
 *
659
 * @returns ::NC_NOERR No error.
660
 * @returns ::NC_EPERM Attempting to create a netCDF file in a directory where you do not have permission to open files.
661
 * @returns ::NC_ENFILE Too many files open
662
 * @returns ::NC_ENOMEM Out of memory.
663
 * @returns ::NC_EHDFERR HDF5 error. (NetCDF-4 files only.)
664
 * @returns ::NC_EDIMMETA Error in netCDF-4 dimension metadata. (NetCDF-4 files only.)
665
 *
666
 * <h1>Examples</h1>
667
 *
668
 * Here is an example using nc_open()to open an existing netCDF dataset
669
 * named foo.nc for read-only, non-shared access:
670
 *
671
 * @code
672
 * #include <netcdf.h>
673
 *   ...
674
 * int status = NC_NOERR;
675
 * int ncid;
676
 *   ...
677
 * status = nc_open("foo.nc", 0, &ncid);
678
 * if (status != NC_NOERR) handle_error(status);
679
 * @endcode
680
 * @ingroup datasets
681
 * @author Glenn Davis, Ed Hartnett, Dennis Heimbigner
682
 */
683
int
684
nc_open(const char *path, int omode, int *ncidp)
685
0
{
686
0
    return NC_open(path, omode, 0, NULL, 0, NULL, ncidp);
687
0
}
688
689
/** \ingroup datasets
690
    Open a netCDF file with extra performance parameters for the classic
691
    library.
692
693
    \param path File name for netCDF dataset to be opened. When DAP
694
    support is enabled, then the path may be an OPeNDAP URL rather than a
695
    file path.
696
697
    \param omode The open mode flag may include NC_WRITE (for read/write
698
    access) and NC_SHARE as in nc_open().
699
700
    \param chunksizehintp A size hint for the classic library. Only
701
    applies to classic files. See below for more
702
    information.
703
704
    \param ncidp Pointer to location where returned netCDF ID is to be
705
    stored.
706
707
    <h1>The chunksizehintp Parameter</h1>
708
709
    The argument referenced by bufrsizehintp controls a space versus time
710
    tradeoff, memory allocated in the netcdf library versus number of
711
    system calls.
712
713
    Because of internal requirements, the value may not be set to exactly
714
    the value requested. The actual value chosen is returned by reference.
715
716
    Using a NULL pointer or having the pointer point to the value
717
    NC_SIZEHINT_DEFAULT causes the library to choose a default.
718
    How the system chooses the default depends on the system. On
719
    many systems, the "preferred I/O block size" is available from the
720
    stat() system call, struct stat member st_blksize. If this is
721
    available it is used. Lacking that, twice the system pagesize is used.
722
723
    Lacking a call to discover the system pagesize, we just set default
724
    bufrsize to 8192.
725
726
    The bufrsize is a property of a given open netcdf descriptor ncid, it
727
    is not a persistent property of the netcdf dataset.
728
729
730
    \returns ::NC_NOERR No error.
731
732
    \returns ::NC_ENOMEM Out of memory.
733
734
    \returns ::NC_EHDFERR HDF5 error. (NetCDF-4 files only.)
735
736
    \returns ::NC_EDIMMETA Error in netCDF-4 dimension metadata. (NetCDF-4
737
    files only.)
738
739
*/
740
int
741
nc__open(const char *path, int omode,
742
         size_t *chunksizehintp, int *ncidp)
743
0
{
744
    /* this API is for non-parallel access.
745
     * Note nc_open_par() also calls NC_open().
746
     */
747
0
    return NC_open(path, omode, 0, chunksizehintp, 0, NULL, ncidp);
748
0
}
749
750
/** \ingroup datasets
751
    Open a netCDF file with the contents taken from a block of memory.
752
753
    \param path Must be non-null, but otherwise only used to set the dataset name.
754
755
    \param omode the open mode flags; Note that this procedure uses a limited set of flags because it forcibly sets NC_INMEMORY.
756
757
    \param size The length of the block of memory being passed.
758
759
    \param memory Pointer to the block of memory containing the contents
760
    of a netcdf file.
761
762
    \param ncidp Pointer to location where returned netCDF ID is to be
763
    stored.
764
765
    \returns ::NC_NOERR No error.
766
767
    \returns ::NC_ENOMEM Out of memory.
768
769
    \returns ::NC_EDISKLESS diskless io is not enabled for fails.
770
771
    \returns ::NC_EINVAL, etc. other errors also returned by nc_open.
772
773
    <h1>Examples</h1>
774
775
    Here is an example using nc_open_mem() to open an existing netCDF dataset
776
    named foo.nc for read-only, non-shared access. It differs from the nc_open()
777
    example in that it assumes the contents of foo.nc have been read into memory.
778
779
    @code
780
    #include <netcdf.h>
781
    #include <netcdf_mem.h>
782
    ...
783
    int status = NC_NOERR;
784
    int ncid;
785
    size_t size;
786
    void* memory;
787
    ...
788
    size = <compute file size of foo.nc in bytes>;
789
    memory = malloc(size);
790
    ...
791
    status = nc_open_mem("foo.nc", 0, size, memory, &ncid);
792
    if (status != NC_NOERR) handle_error(status);
793
    @endcode
794
*/
795
int
796
nc_open_mem(const char* path, int omode, size_t size, void* memory, int* ncidp)
797
77
{
798
77
    NC_memio meminfo;
799
800
    /* Sanity checks */
801
77
    if(memory == NULL || size < MAGIC_NUMBER_LEN || path == NULL)
802
0
        return NC_EINVAL;
803
77
    if(omode & (NC_WRITE|NC_MMAP))
804
0
        return NC_EINVAL;
805
77
    omode |= (NC_INMEMORY); /* Note: NC_INMEMORY and NC_DISKLESS are mutually exclusive*/
806
77
    meminfo.size = size;
807
77
    meminfo.memory = memory;
808
77
    meminfo.flags = NC_MEMIO_LOCKED;
809
77
    return NC_open(path, omode, 0, NULL, 0, &meminfo, ncidp);
810
77
}
811
812
/** \ingroup datasets
813
    Open a netCDF file with the contents taken from a block of memory.
814
    Similar to nc_open_mem, but with parameters. Warning: if you do
815
    specify that the provided memory is locked, then <b>never</b>
816
    pass in non-heap allocated memory. Additionally, if not locked,
817
    then do not assume that the memory returned by nc_close_mem
818
    is the same as passed to nc_open_memio. You <b>must</b> check
819
    before attempting to free the original memory.
820
821
    \param path Must be non-null, but otherwise only used to set the dataset name.
822
823
    \param omode the open mode flags; Note that this procedure uses a limited set of flags because it forcibly sets NC_INMEMORY.
824
825
    \param params controlling parameters
826
827
    \param ncidp Pointer to location where returned netCDF ID is to be
828
    stored.
829
830
    \returns ::NC_NOERR No error.
831
832
    \returns ::NC_ENOMEM Out of memory.
833
834
    \returns ::NC_EDISKLESS diskless io is not enabled for fails.
835
836
    \returns ::NC_EINVAL, etc. other errors also returned by nc_open.
837
838
    <h1>Examples</h1>
839
840
    Here is an example using nc_open_memio() to open an existing netCDF dataset
841
    named foo.nc for read-only, non-shared access. It differs from the nc_open_mem()
842
    example in that it uses a parameter block.
843
844
    @code
845
    #include <netcdf.h>
846
    #include <netcdf_mem.h>
847
    ...
848
    int status = NC_NOERR;
849
    int ncid;
850
    NC_memio params;
851
    ...
852
    params.size = <compute file size of foo.nc in bytes>;
853
    params.memory = malloc(size);
854
    params.flags = <see netcdf_mem.h>
855
    ...
856
    status = nc_open_memio("foo.nc", 0, &params, &ncid);
857
    if (status != NC_NOERR) handle_error(status);
858
    @endcode
859
*/
860
int
861
nc_open_memio(const char* path, int omode, NC_memio* params, int* ncidp)
862
0
{
863
    /* Sanity checks */
864
0
    if(path == NULL || params == NULL)
865
0
        return NC_EINVAL;
866
0
    if(params->memory == NULL || params->size < MAGIC_NUMBER_LEN)
867
0
        return NC_EINVAL;
868
869
0
    if(omode & NC_MMAP)
870
0
        return NC_EINVAL;
871
0
    omode |= (NC_INMEMORY);
872
0
    return NC_open(path, omode, 0, NULL, 0, params, ncidp);
873
0
}
874
875
/**
876
 * @internal Open a netCDF file with extra parameters for Cray.
877
 *
878
 * @deprecated This function was used in the old days with the Cray at
879
 * NCAR. The Cray is long gone, and this call is supported only for
880
 * backward compatibility. Use nc_open() instead.
881
 *
882
 * @param path The file name of the new netCDF dataset.
883
 * @param omode Open mode.
884
 * @param basepe Deprecated parameter from the Cray days.
885
 * @param chunksizehintp A pointer to the chunk size hint. This only
886
 * applies to classic files.
887
 * @param ncidp Pointer to location where returned netCDF ID is to be
888
 * stored.
889
 *
890
 * @return ::NC_NOERR
891
 * @author Glenn Davis
892
 */
893
int
894
nc__open_mp(const char *path, int omode, int basepe,
895
            size_t *chunksizehintp, int *ncidp)
896
0
{
897
0
    return NC_open(path, omode, basepe, chunksizehintp, 0, NULL, ncidp);
898
0
}
899
900
/** \ingroup datasets
901
    Get the file pathname (or the opendap URL) which was used to
902
    open/create the ncid's file.
903
904
    \param ncid NetCDF ID, from a previous call to nc_open() or
905
    nc_create().
906
907
    \param pathlen Pointer where length of path will be returned. Ignored
908
    if NULL.
909
910
    \param path Pointer where path name will be copied. Space must already
911
    be allocated. Ignored if NULL.
912
913
    \returns ::NC_NOERR No error.
914
915
    \returns ::NC_EBADID Invalid ncid passed.
916
*/
917
int
918
nc_inq_path(int ncid, size_t *pathlen, char *path)
919
0
{
920
0
    NC* ncp;
921
0
    int stat = NC_NOERR;
922
0
    if ((stat = NC_check_id(ncid, &ncp)))
923
0
        return stat;
924
0
    if(ncp->path == NULL) {
925
0
        if(pathlen) *pathlen = 0;
926
0
        if(path) path[0] = '\0';
927
0
    } else {
928
0
        if (pathlen) *pathlen = strlen(ncp->path);
929
0
        if (path) strcpy(path, ncp->path);
930
0
    }
931
0
    return stat;
932
0
}
933
934
/** \ingroup datasets
935
    Put open netcdf dataset into define mode
936
937
    The function nc_redef puts an open netCDF dataset into define mode, so
938
    dimensions, variables, and attributes can be added or renamed and
939
    attributes can be deleted.
940
941
    For netCDF-4 files (i.e. files created with NC_NETCDF4 in the cmode in
942
    their call to nc_create()), it is not necessary to call nc_redef()
943
    unless the file was also created with NC_STRICT_NC3. For straight-up
944
    netCDF-4 files, nc_redef() is called automatically, as needed.
945
946
    For all netCDF-4 files, the root ncid must be used. This is the ncid
947
    returned by nc_open() and nc_create(), and points to the root of the
948
    hierarchy tree for netCDF-4 files.
949
950
    \param ncid NetCDF ID, from a previous call to nc_open() or
951
    nc_create().
952
953
    \returns ::NC_NOERR No error.
954
955
    \returns ::NC_EBADID Bad ncid.
956
957
    \returns ::NC_EBADGRPID The ncid must refer to the root group of the
958
    file, that is, the group returned by nc_open() or nc_create().
959
960
    \returns ::NC_EINDEFINE Already in define mode.
961
962
    \returns ::NC_EPERM File is read-only.
963
964
    <h1>Example</h1>
965
966
    Here is an example using nc_redef to open an existing netCDF dataset
967
    named foo.nc and put it into define mode:
968
969
    \code
970
    #include <netcdf.h>
971
    ...
972
    int status = NC_NOERR;
973
    int ncid;
974
    ...
975
    status = nc_open("foo.nc", NC_WRITE, &ncid);
976
    if (status != NC_NOERR) handle_error(status);
977
    ...
978
    status = nc_redef(ncid);
979
    if (status != NC_NOERR) handle_error(status);
980
    \endcode
981
*/
982
int
983
nc_redef(int ncid)
984
0
{
985
0
    NC* ncp;
986
0
    int stat = NC_check_id(ncid, &ncp);
987
0
    if(stat != NC_NOERR) return stat;
988
0
    return ncp->dispatch->redef(ncid);
989
0
}
990
991
/** \ingroup datasets
992
    Leave define mode
993
994
    The function nc_enddef() takes an open netCDF dataset out of define
995
    mode. The changes made to the netCDF dataset while it was in define
996
    mode are checked and committed to disk if no problems
997
    occurred. Non-record variables may be initialized to a "fill value" as
998
    well with nc_set_fill(). The netCDF dataset is then placed in data
999
    mode, so variable data can be read or written.
1000
1001
    It's not necessary to call nc_enddef() for netCDF-4 files. With netCDF-4
1002
    files, nc_enddef() is called when needed by the netcdf-4 library. User
1003
    calls to nc_enddef() for netCDF-4 files still flush the metadata to
1004
    disk.
1005
1006
    This call may involve copying data under some circumstances. For a
1007
    more extensive discussion see File Structure and Performance.
1008
1009
    For netCDF-4/HDF5 format files there are some variable settings (the
1010
    compression, endianness, fletcher32 error correction, and fill value)
1011
    which must be set (if they are going to be set at all) between the
1012
    nc_def_var() and the next nc_enddef(). Once the nc_enddef() is called,
1013
    these settings can no longer be changed for a variable.
1014
1015
    \param ncid NetCDF ID, from a previous call to nc_open() or
1016
    nc_create().
1017
1018
    If you use a group id (in a netCDF-4/HDF5 file), the enddef
1019
    will apply to the entire file. That means the enddef will not just end
1020
    define mode in one group, but in the entire file.
1021
1022
    \returns ::NC_NOERR no error
1023
1024
    \returns ::NC_EBADID Invalid ncid passed.
1025
1026
    <h1>Example</h1>
1027
1028
    Here is an example using nc_enddef() to finish the definitions of a new
1029
    netCDF dataset named foo.nc and put it into data mode:
1030
1031
    \code
1032
    #include <netcdf.h>
1033
    ...
1034
    int status = NC_NOERR;
1035
    int ncid;
1036
    ...
1037
    status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
1038
    if (status != NC_NOERR) handle_error(status);
1039
1040
    ...  create dimensions, variables, attributes
1041
1042
    status = nc_enddef(ncid);
1043
    if (status != NC_NOERR) handle_error(status);
1044
    \endcode
1045
*/
1046
int
1047
nc_enddef(int ncid)
1048
0
{
1049
0
    int status = NC_NOERR;
1050
0
    NC *ncp;
1051
0
    status = NC_check_id(ncid, &ncp);
1052
0
    if(status != NC_NOERR) return status;
1053
0
    return ncp->dispatch->_enddef(ncid,0,1,0,1);
1054
0
}
1055
1056
/** \ingroup datasets
1057
    Leave define mode with performance tuning
1058
1059
    The function nc__enddef takes an open netCDF dataset out of define
1060
    mode. The changes made to the netCDF dataset while it was in define
1061
    mode are checked and committed to disk if no problems
1062
    occurred. Non-record variables may be initialized to a "fill value" as
1063
    well with nc_set_fill(). The netCDF dataset is then placed in data mode,
1064
    so variable data can be read or written.
1065
1066
    This call may involve copying data under some circumstances. For a
1067
    more extensive discussion see File Structure and Performance.
1068
1069
    \warning This function exposes internals of the netcdf version 1 file
1070
    format. Users should use nc_enddef() in most circumstances. This
1071
    function may not be available on future netcdf implementations.
1072
1073
    The classic netcdf file format has three sections, the "header"
1074
    section, the data section for fixed size variables, and the data
1075
    section for variables which have an unlimited dimension (record
1076
    variables).
1077
1078
    The header begins at the beginning of the file. The index (offset) of
1079
    the beginning of the other two sections is contained in the
1080
    header. Typically, there is no space between the sections. This causes
1081
    copying overhead to accrue if one wishes to change the size of the
1082
    sections, as may happen when changing names of things, text attribute
1083
    values, adding attributes or adding variables. Also, for buffered i/o,
1084
    there may be advantages to aligning sections in certain ways.
1085
1086
    The minfree parameters allow one to control costs of future calls to
1087
    nc_redef, nc_enddef() by requesting that minfree bytes be available at
1088
    the end of the section.
1089
1090
    The align parameters allow one to set the alignment of the beginning
1091
    of the corresponding sections. The beginning of the section is rounded
1092
    up to an index which is a multiple of the align parameter. The flag
1093
    value ALIGN_CHUNK tells the library to use the bufrsize (see above) as
1094
    the align parameter. It has nothing to do with the chunking
1095
    (multidimensional tiling) features of netCDF-4.
1096
1097
    The file format requires mod 4 alignment, so the align parameters are
1098
    silently rounded up to multiples of 4. The usual call,
1099
1100
    \code
1101
    nc_enddef(ncid);
1102
    \endcode
1103
1104
    is equivalent to
1105
1106
    \code
1107
    nc__enddef(ncid, 0, 4, 0, 4);
1108
    \endcode
1109
1110
    The file format does not contain a "record size" value, this is
1111
    calculated from the sizes of the record variables. This unfortunate
1112
    fact prevents us from providing minfree and alignment control of the
1113
    "records" in a netcdf file. If you add a variable which has an
1114
    unlimited dimension, the third section will always be copied with the
1115
    new variable added.
1116
1117
    \param ncid NetCDF ID, from a previous call to nc_open() or
1118
    nc_create().
1119
1120
    \param h_minfree Sets the pad at the end of the "header" section.
1121
1122
    \param v_align Controls the alignment of the beginning of the data
1123
    section for fixed size variables.
1124
1125
    \param v_minfree Sets the pad at the end of the data section for fixed
1126
    size variables.
1127
1128
    \param r_align Controls the alignment of the beginning of the data
1129
    section for variables which have an unlimited dimension (record
1130
    variables).
1131
1132
    \returns ::NC_NOERR No error.
1133
1134
    \returns ::NC_EBADID Invalid ncid passed.
1135
1136
*/
1137
int
1138
nc__enddef(int ncid, size_t h_minfree, size_t v_align, size_t v_minfree,
1139
           size_t r_align)
1140
0
{
1141
0
    NC* ncp;
1142
0
    int stat = NC_check_id(ncid, &ncp);
1143
0
    if(stat != NC_NOERR) return stat;
1144
0
    return ncp->dispatch->_enddef(ncid,h_minfree,v_align,v_minfree,r_align);
1145
0
}
1146
1147
/** \ingroup datasets
1148
    Synchronize an open netcdf dataset to disk
1149
1150
    The function nc_sync() offers a way to synchronize the disk copy of a
1151
    netCDF dataset with in-memory buffers. There are two reasons you might
1152
    want to synchronize after writes:
1153
    - To minimize data loss in case of abnormal termination, or
1154
    - To make data available to other processes for reading immediately
1155
    after it is written. But note that a process that already had the
1156
    dataset open for reading would not see the number of records
1157
    increase when the writing process calls nc_sync(); to accomplish this,
1158
    the reading process must call nc_sync.
1159
1160
    This function is backward-compatible with previous versions of the
1161
    netCDF library. The intent was to allow sharing of a netCDF dataset
1162
    among multiple readers and one writer, by having the writer call
1163
    nc_sync() after writing and the readers call nc_sync() before each
1164
    read. For a writer, this flushes buffers to disk. For a reader, it
1165
    makes sure that the next read will be from disk rather than from
1166
    previously cached buffers, so that the reader will see changes made by
1167
    the writing process (e.g., the number of records written) without
1168
    having to close and reopen the dataset. If you are only accessing a
1169
    small amount of data, it can be expensive in computer resources to
1170
    always synchronize to disk after every write, since you are giving up
1171
    the benefits of buffering.
1172
1173
    An easier way to accomplish sharing (and what is now recommended) is
1174
    to have the writer and readers open the dataset with the NC_SHARE
1175
    flag, and then it will not be necessary to call nc_sync() at
1176
    all. However, the nc_sync() function still provides finer granularity
1177
    than the NC_SHARE flag, if only a few netCDF accesses need to be
1178
    synchronized among processes.
1179
1180
    It is important to note that changes to the ancillary data, such as
1181
    attribute values, are not propagated automatically by use of the
1182
    NC_SHARE flag. Use of the nc_sync() function is still required for this
1183
    purpose.
1184
1185
    Sharing datasets when the writer enters define mode to change the data
1186
    schema requires extra care. In previous releases, after the writer
1187
    left define mode, the readers were left looking at an old copy of the
1188
    dataset, since the changes were made to a new copy. The only way
1189
    readers could see the changes was by closing and reopening the
1190
    dataset. Now the changes are made in place, but readers have no
1191
    knowledge that their internal tables are now inconsistent with the new
1192
    dataset schema. If netCDF datasets are shared across redefinition,
1193
    some mechanism external to the netCDF library must be provided that
1194
    prevents access by readers during redefinition and causes the readers
1195
    to call nc_sync before any subsequent access.
1196
1197
    When calling nc_sync(), the netCDF dataset must be in data mode. A
1198
    netCDF dataset in define mode is synchronized to disk only when
1199
    nc_enddef() is called. A process that is reading a netCDF dataset that
1200
    another process is writing may call nc_sync to get updated with the
1201
    changes made to the data by the writing process (e.g., the number of
1202
    records written), without having to close and reopen the dataset.
1203
1204
    Data is automatically synchronized to disk when a netCDF dataset is
1205
    closed, or whenever you leave define mode.
1206
1207
    \param ncid NetCDF ID, from a previous call to nc_open() or
1208
    nc_create().
1209
1210
    \returns ::NC_NOERR No error.
1211
1212
    \returns ::NC_EBADID Invalid ncid passed.
1213
*/
1214
int
1215
nc_sync(int ncid)
1216
0
{
1217
0
    NC* ncp;
1218
0
    int stat = NC_check_id(ncid, &ncp);
1219
0
    if(stat != NC_NOERR) return stat;
1220
0
    return ncp->dispatch->sync(ncid);
1221
0
}
1222
1223
/** \ingroup datasets
1224
    No longer necessary for user to invoke manually.
1225
1226
1227
    \warning Users no longer need to call this function since it is called
1228
    automatically by nc_close() in case the dataset is in define mode and
1229
    something goes wrong with committing the changes. The function
1230
    nc_abort() just closes the netCDF dataset, if not in define mode. If
1231
    the dataset is being created and is still in define mode, the dataset
1232
    is deleted. If define mode was entered by a call to nc_redef(), the
1233
    netCDF dataset is restored to its state before definition mode was
1234
    entered and the dataset is closed.
1235
1236
    \param ncid NetCDF ID, from a previous call to nc_open() or
1237
    nc_create().
1238
1239
    \returns ::NC_NOERR No error.
1240
1241
    <h1>Example</h1>
1242
1243
    Here is an example using nc_abort to back out of redefinitions of a
1244
    dataset named foo.nc:
1245
1246
    \code
1247
    #include <netcdf.h>
1248
    ...
1249
    int ncid, status, latid;
1250
    ...
1251
    status = nc_open("foo.nc", NC_WRITE, &ncid);
1252
    if (status != NC_NOERR) handle_error(status);
1253
    ...
1254
    status = nc_redef(ncid);
1255
    if (status != NC_NOERR) handle_error(status);
1256
    ...
1257
    status = nc_def_dim(ncid, "lat", 18L, &latid);
1258
    if (status != NC_NOERR) {
1259
    handle_error(status);
1260
    status = nc_abort(ncid);
1261
    if (status != NC_NOERR) handle_error(status);
1262
    }
1263
    \endcode
1264
1265
*/
1266
int
1267
nc_abort(int ncid)
1268
0
{
1269
0
    NC* ncp;
1270
0
    int stat = NC_check_id(ncid, &ncp);
1271
0
    if(stat != NC_NOERR) return stat;
1272
1273
0
    stat = ncp->dispatch->abort(ncid);
1274
0
    del_from_NCList(ncp);
1275
0
    free_NC(ncp);
1276
0
    return stat;
1277
0
}
1278
1279
/** \ingroup datasets
1280
    Close an open netCDF dataset
1281
1282
    If the dataset in define mode, nc_enddef() will be called before
1283
    closing. (In this case, if nc_enddef() returns an error, nc_abort() will
1284
    automatically be called to restore the dataset to the consistent state
1285
    before define mode was last entered.) After an open netCDF dataset is
1286
    closed, its netCDF ID may be reassigned to the next netCDF dataset
1287
    that is opened or created.
1288
1289
    \param ncid NetCDF ID, from a previous call to nc_open() or nc_create().
1290
1291
    \returns ::NC_NOERR No error.
1292
1293
    \returns ::NC_EBADID Invalid id passed.
1294
1295
    \returns ::NC_EBADGRPID ncid did not contain the root group id of this
1296
    file. (NetCDF-4 only).
1297
1298
    <h1>Example</h1>
1299
1300
    Here is an example using nc_close to finish the definitions of a new
1301
    netCDF dataset named foo.nc and release its netCDF ID:
1302
1303
    \code
1304
    #include <netcdf.h>
1305
    ...
1306
    int status = NC_NOERR;
1307
    int ncid;
1308
    ...
1309
    status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
1310
    if (status != NC_NOERR) handle_error(status);
1311
1312
    ...   create dimensions, variables, attributes
1313
1314
    status = nc_close(ncid);
1315
    if (status != NC_NOERR) handle_error(status);
1316
    \endcode
1317
1318
*/
1319
int
1320
nc_close(int ncid)
1321
5
{
1322
5
    NC* ncp;
1323
5
    int stat = NC_check_id(ncid, &ncp);
1324
5
    if(stat != NC_NOERR) return stat;
1325
1326
5
    stat = ncp->dispatch->close(ncid,NULL);
1327
    /* Remove from the nc list */
1328
5
    if (!stat)
1329
5
    {
1330
5
        del_from_NCList(ncp);
1331
5
        free_NC(ncp);
1332
5
    }
1333
5
    return stat;
1334
5
}
1335
1336
/** \ingroup datasets
1337
    Do a normal close (see nc_close()) on an in-memory dataset,
1338
    then return a copy of the final memory contents of the dataset.
1339
1340
    \param ncid NetCDF ID, from a previous call to nc_open() or nc_create().
1341
1342
    \param memio a pointer to an NC_memio object into which the final valid memory
1343
    size and memory will be returned.
1344
1345
    \returns ::NC_NOERR No error.
1346
1347
    \returns ::NC_EBADID Invalid id passed.
1348
1349
    \returns ::NC_ENOMEM Out of memory.
1350
1351
    \returns ::NC_EDISKLESS if the file was not created as an inmemory file.
1352
1353
    \returns ::NC_EBADGRPID ncid did not contain the root group id of this
1354
    file. (NetCDF-4 only).
1355
1356
    <h1>Example</h1>
1357
1358
    Here is an example using nc_close_mem to finish the definitions of a new
1359
    netCDF dataset named foo.nc, return the final memory,
1360
    and release its netCDF ID:
1361
1362
    \code
1363
    #include <netcdf.h>
1364
    ...
1365
    int status = NC_NOERR;
1366
    int ncid;
1367
    NC_memio finalmem;
1368
    size_t initialsize = 65000;
1369
    ...
1370
    status = nc_create_mem("foo.nc", NC_NOCLOBBER, initialsize, &ncid);
1371
    if (status != NC_NOERR) handle_error(status);
1372
    ...   create dimensions, variables, attributes
1373
    status = nc_close_memio(ncid,&finalmem);
1374
    if (status != NC_NOERR) handle_error(status);
1375
    \endcode
1376
1377
*/
1378
int
1379
nc_close_memio(int ncid, NC_memio* memio)
1380
0
{
1381
0
    NC* ncp;
1382
0
    int stat = NC_check_id(ncid, &ncp);
1383
0
    if(stat != NC_NOERR) return stat;
1384
1385
0
    stat = ncp->dispatch->close(ncid,memio);
1386
    /* Remove from the nc list */
1387
0
    if (!stat)
1388
0
    {
1389
0
        del_from_NCList(ncp);
1390
0
        free_NC(ncp);
1391
0
    }
1392
0
    return stat;
1393
0
}
1394
1395
/** \ingroup datasets
1396
    Change the fill-value mode to improve write performance.
1397
1398
    This function is intended for advanced usage, to optimize writes under
1399
    some circumstances described below. The function nc_set_fill() sets the
1400
    fill mode for a netCDF dataset open for writing and returns the
1401
    current fill mode in a return parameter. The fill mode can be
1402
    specified as either ::NC_FILL or ::NC_NOFILL. The default behavior
1403
    corresponding to ::NC_FILL is that data is pre-filled with fill values,
1404
    that is fill values are written when you create non-record variables
1405
    or when you write a value beyond data that has not yet been
1406
    written. This makes it possible to detect attempts to read data before
1407
    it was written. For more information on the use of fill values see
1408
    Fill Values. For information about how to define your own fill values
1409
    see Attribute Conventions.
1410
1411
    The behavior corresponding to ::NC_NOFILL overrides the default behavior
1412
    of prefilling data with fill values. This can be used to enhance
1413
    performance, because it avoids the duplicate writes that occur when
1414
    the netCDF library writes fill values that are later overwritten with
1415
    data.
1416
1417
    A value indicating which mode the netCDF dataset was already in is
1418
    returned. You can use this value to temporarily change the fill mode
1419
    of an open netCDF dataset and then restore it to the previous mode.
1420
1421
    After you turn on ::NC_NOFILL mode for an open netCDF dataset, you must
1422
    be certain to write valid data in all the positions that will later be
1423
    read. Note that nofill mode is only a transient property of a netCDF
1424
    dataset open for writing: if you close and reopen the dataset, it will
1425
    revert to the default behavior. You can also revert to the default
1426
    behavior by calling nc_set_fill() again to explicitly set the fill mode
1427
    to ::NC_FILL.
1428
1429
    There are three situations where it is advantageous to set nofill
1430
    mode:
1431
    - Creating and initializing a netCDF dataset. In this case, you should
1432
    set nofill mode before calling nc_enddef() and then write completely
1433
    all non-record variables and the initial records of all the record
1434
    variables you want to initialize.
1435
    - Extending an existing record-oriented netCDF dataset. Set nofill
1436
    mode after opening the dataset for writing, then append the
1437
    additional records to the dataset completely, leaving no intervening
1438
    unwritten records.
1439
    - Adding new variables that you are going to initialize to an existing
1440
    netCDF dataset. Set nofill mode before calling nc_enddef() then write
1441
    all the new variables completely.
1442
1443
    If the netCDF dataset has an unlimited dimension and the last record
1444
    was written while in nofill mode, then the dataset may be shorter than
1445
    if nofill mode was not set, but this will be completely transparent if
1446
    you access the data only through the netCDF interfaces.
1447
1448
    The use of this feature may not be available (or even needed) in
1449
    future releases. Programmers are cautioned against heavy reliance upon
1450
    this feature.
1451
1452
    \param ncid NetCDF ID, from a previous call to nc_open() or
1453
    nc_create().
1454
1455
    \param fillmode Desired fill mode for the dataset, either ::NC_NOFILL or
1456
    ::NC_FILL.
1457
1458
    \param old_modep Pointer to location for returned current fill mode of
1459
    the dataset before this call, either ::NC_NOFILL or ::NC_FILL.
1460
1461
    \returns ::NC_NOERR No error.
1462
1463
    \returns ::NC_EBADID The specified netCDF ID does not refer to an open
1464
    netCDF dataset.
1465
1466
    \returns ::NC_EPERM The specified netCDF ID refers to a dataset open for
1467
    read-only access.
1468
1469
    \returns ::NC_EINVAL The fill mode argument is neither ::NC_NOFILL nor
1470
    ::NC_FILL.
1471
1472
    <h1>Example</h1>
1473
1474
    Here is an example using nc_set_fill() to set nofill mode for subsequent
1475
    writes of a netCDF dataset named foo.nc:
1476
1477
    \code
1478
    #include <netcdf.h>
1479
    ...
1480
    int ncid, status, old_fill_mode;
1481
    ...
1482
    status = nc_open("foo.nc", NC_WRITE, &ncid);
1483
    if (status != NC_NOERR) handle_error(status);
1484
1485
    ...     write data with default prefilling behavior
1486
1487
    status = nc_set_fill(ncid, ::NC_NOFILL, &old_fill_mode);
1488
    if (status != NC_NOERR) handle_error(status);
1489
1490
    ...    write data with no prefilling
1491
    \endcode
1492
*/
1493
int
1494
nc_set_fill(int ncid, int fillmode, int *old_modep)
1495
0
{
1496
0
    NC* ncp;
1497
0
    int stat = NC_check_id(ncid, &ncp);
1498
0
    if(stat != NC_NOERR) return stat;
1499
0
    return ncp->dispatch->set_fill(ncid,fillmode,old_modep);
1500
0
}
1501
1502
/**
1503
 * @internal Learn base PE.
1504
 *
1505
 * @deprecated This function was used in the old days with the Cray at
1506
 * NCAR. The Cray is long gone, and this call is now meaningless. The
1507
 * value returned for pe is always 0.
1508
 *
1509
 * @param ncid File and group ID.
1510
 * @param pe Pointer for base PE.
1511
 *
1512
 * @return ::NC_NOERR No error.
1513
 * @return ::NC_EBADID Invalid ncid passed.
1514
 * @author Glenn Davis
1515
 */
1516
int
1517
nc_inq_base_pe(int ncid, int *pe)
1518
0
{
1519
0
    NC* ncp;
1520
0
    int stat = NC_check_id(ncid, &ncp);
1521
0
    if(stat != NC_NOERR) return stat;
1522
0
    if (pe) *pe = 0;
1523
0
    return NC_NOERR;
1524
0
}
1525
1526
/**
1527
 * @internal Sets base processing element (ignored).
1528
 *
1529
 * @deprecated This function was used in the old days with the Cray at
1530
 * NCAR. The Cray is long gone, and this call is supported only for
1531
 * backward compatibility.
1532
 *
1533
 * @param ncid File ID.
1534
 * @param pe Base PE.
1535
 *
1536
 * @return ::NC_NOERR No error.
1537
 * @return ::NC_EBADID Invalid ncid passed.
1538
 * @author Glenn Davis
1539
 */
1540
int
1541
nc_set_base_pe(int ncid, int pe)
1542
0
{
1543
0
    NC* ncp;
1544
0
    int stat = NC_check_id(ncid, &ncp);
1545
0
    if(stat != NC_NOERR) return stat;
1546
0
    return NC_NOERR;
1547
0
}
1548
1549
/**
1550
 * @ingroup datasets
1551
 * Inquire about the binary format of a netCDF file
1552
 * as presented by the API.
1553
 *
1554
 * This function returns the (rarely needed) format version.
1555
 *
1556
 * @param ncid NetCDF ID, from a previous call to nc_open() or
1557
 * nc_create().
1558
 * @param formatp Pointer to location for returned format version, one
1559
 * of NC_FORMAT_CLASSIC, NC_FORMAT_64BIT_OFFSET, NC_FORMAT_CDF5,
1560
 * NC_FORMAT_NETCDF4, NC_FORMAT_NETCDF4_CLASSIC.
1561
 *
1562
 * @returns ::NC_NOERR No error.
1563
 * @returns ::NC_EBADID Invalid ncid passed.
1564
 * @author Dennis Heimbigner
1565
 */
1566
int
1567
nc_inq_format(int ncid, int *formatp)
1568
0
{
1569
0
    NC* ncp;
1570
0
    int stat = NC_check_id(ncid, &ncp);
1571
0
    if(stat != NC_NOERR) return stat;
1572
0
    return ncp->dispatch->inq_format(ncid,formatp);
1573
0
}
1574
1575
/** \ingroup datasets
1576
    Obtain more detailed (vis-a-vis nc_inq_format)
1577
    format information about an open dataset.
1578
1579
    Note that the netcdf API will present the file
1580
    as if it had the format specified by nc_inq_format.
1581
    The true file format, however, may not even be
1582
    a netcdf file; it might be DAP, HDF4, or PNETCDF,
1583
    for example. This function returns that true file type.
1584
    It also returns the effective mode for the file.
1585
1586
    \param ncid NetCDF ID, from a previous call to nc_open() or
1587
    nc_create().
1588
1589
    \param formatp Pointer to location for returned true format.
1590
1591
    \param modep Pointer to location for returned mode flags.
1592
1593
    Refer to the actual list in the file netcdf.h to see the
1594
    currently defined set.
1595
1596
    \returns ::NC_NOERR No error.
1597
1598
    \returns ::NC_EBADID Invalid ncid passed.
1599
1600
*/
1601
int
1602
nc_inq_format_extended(int ncid, int *formatp, int *modep)
1603
0
{
1604
0
    NC* ncp;
1605
0
    int stat = NC_check_id(ncid, &ncp);
1606
0
    if(stat != NC_NOERR) return stat;
1607
0
    return ncp->dispatch->inq_format_extended(ncid,formatp,modep);
1608
0
}
1609
1610
/**\ingroup datasets
1611
   Inquire about a file or group.
1612
1613
   \param ncid NetCDF or group ID, from a previous call to nc_open(),
1614
   nc_create(), nc_def_grp(), or associated inquiry functions such as
1615
   nc_inq_ncid().
1616
1617
   \param ndimsp Pointer to location for returned number of dimensions
1618
   defined for this netCDF dataset. Ignored if NULL.
1619
1620
   \param nvarsp Pointer to location for returned number of variables
1621
   defined for this netCDF dataset. Ignored if NULL.
1622
1623
   \param nattsp Pointer to location for returned number of global
1624
   attributes defined for this netCDF dataset. Ignored if NULL.
1625
1626
   \param unlimdimidp Pointer to location for returned ID of the
1627
   unlimited dimension, if there is one for this netCDF dataset. If no
1628
   unlimited length dimension has been defined, -1 is returned. Ignored
1629
   if NULL.  If there are multiple unlimited dimensions (possible only
1630
   for netCDF-4 files), only a pointer to the first is returned, for
1631
   backward compatibility.  If you want them all, use nc_inq_unlimids().
1632
1633
   \returns ::NC_NOERR No error.
1634
1635
   \returns ::NC_EBADID Invalid ncid passed.
1636
1637
   <h1>Example</h1>
1638
1639
   Here is an example using nc_inq to find out about a netCDF dataset
1640
   named foo.nc:
1641
1642
   \code
1643
   #include <netcdf.h>
1644
   ...
1645
   int status, ncid, ndims, nvars, ngatts, unlimdimid;
1646
   ...
1647
   status = nc_open("foo.nc", NC_NOWRITE, &ncid);
1648
   if (status != NC_NOERR) handle_error(status);
1649
   ...
1650
   status = nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid);
1651
   if (status != NC_NOERR) handle_error(status);
1652
   \endcode
1653
*/
1654
int
1655
nc_inq(int ncid, int *ndimsp, int *nvarsp, int *nattsp, int *unlimdimidp)
1656
0
{
1657
0
    NC* ncp;
1658
0
    int stat = NC_check_id(ncid, &ncp);
1659
0
    if(stat != NC_NOERR) return stat;
1660
0
    return ncp->dispatch->inq(ncid,ndimsp,nvarsp,nattsp,unlimdimidp);
1661
0
}
1662
1663
/**
1664
 * Learn the number of variables in a file or group.
1665
 *
1666
 * @param ncid File and group ID.
1667
 * @param nvarsp Pointer that gets number of variables. Ignored if NULL.
1668
 *
1669
 * @return ::NC_NOERR No error.
1670
 * @return ::NC_EBADID Bad ncid.
1671
 * @author Glenn Davis, Ed Hartnett, Dennis Heimbigner
1672
 */
1673
int
1674
nc_inq_nvars(int ncid, int *nvarsp)
1675
0
{
1676
0
    NC* ncp;
1677
0
    int stat = NC_check_id(ncid, &ncp);
1678
0
    if(stat != NC_NOERR) return stat;
1679
0
    return ncp->dispatch->inq(ncid, NULL, nvarsp, NULL, NULL);
1680
0
}
1681
1682
/**\ingroup datasets
1683
   Inquire about a type.
1684
1685
   Given an ncid and a typeid, get the information about a type. This
1686
   function will work on any type, including atomic and any user defined
1687
   type, whether compound, opaque, enumeration, or variable length array.
1688
1689
   For even more information about a user defined type nc_inq_user_type().
1690
1691
   \param ncid The ncid for the group containing the type (ignored for
1692
   atomic types).
1693
1694
   \param xtype The typeid for this type, as returned by nc_def_compound,
1695
   nc_def_opaque, nc_def_enum, nc_def_vlen, or nc_inq_var, or as found in
1696
   netcdf.h in the list of atomic types (NC_CHAR, NC_INT, etc.).
1697
1698
   \param name If non-NULL, the name of the user defined type will be
1699
   copied here. It will be NC_MAX_NAME bytes or less. For atomic types,
1700
   the type name from CDL will be given.
1701
1702
   \param size If non-NULL, the (in-memory) size of the type in bytes
1703
   will be copied here. VLEN type size is the size of nc_vlen_t. String
1704
   size is returned as the size of a character pointer. The size may be
1705
   used to malloc space for the data, no matter what the type.
1706
1707
   \returns ::NC_NOERR No error.
1708
1709
   \returns ::NC_EBADTYPE Bad typeid.
1710
1711
   \returns ::NC_ENOTNC4 Seeking a user-defined type in a netCDF-3 file.
1712
1713
   \returns ::NC_ESTRICTNC3 Seeking a user-defined type in a netCDF-4 file
1714
   for which classic model has been turned on.
1715
1716
   \returns ::NC_EBADGRPID Bad group ID in ncid.
1717
1718
   \returns ::NC_EBADID Type ID not found.
1719
1720
   \returns ::NC_EHDFERR An error was reported by the HDF5 layer.
1721
1722
   <h1>Example</h1>
1723
1724
   This example is from the test program tst_enums.c, and it uses all the
1725
   possible inquiry functions on an enum type.
1726
1727
   \code
1728
   if (nc_inq_user_type(ncid, typeids[0], name_in, &base_size_in, &base_nc_type_in,
1729
   &nfields_in, &class_in)) ERR;
1730
   if (strcmp(name_in, TYPE_NAME) || base_size_in != sizeof(int) ||
1731
   base_nc_type_in != NC_INT || nfields_in != NUM_MEMBERS || class_in != NC_ENUM) ERR;
1732
   if (nc_inq_type(ncid, typeids[0], name_in, &base_size_in)) ERR;
1733
   if (strcmp(name_in, TYPE_NAME) || base_size_in != sizeof(int)) ERR;
1734
   if (nc_inq_enum(ncid, typeids[0], name_in, &base_nc_type, &base_size_in, &num_members)) ERR;
1735
   if (strcmp(name_in, TYPE_NAME) || base_nc_type != NC_INT || num_members != NUM_MEMBERS) ERR;
1736
   for (i = 0; i < NUM_MEMBERS; i++)
1737
   {
1738
   if (nc_inq_enum_member(ncid, typeid, i, name_in, &value_in)) ERR;
1739
   if (strcmp(name_in, member_name[i]) || value_in != member_value[i]) ERR;
1740
   if (nc_inq_enum_ident(ncid, typeid, member_value[i], name_in)) ERR;
1741
   if (strcmp(name_in, member_name[i])) ERR;
1742
   }
1743
1744
   if (nc_close(ncid)) ERR;
1745
   \endcode
1746
*/
1747
int
1748
nc_inq_type(int ncid, nc_type xtype, char *name, size_t *size)
1749
0
{
1750
0
    NC* ncp;
1751
0
    int stat;
1752
1753
    /* Do a quick triage on xtype */
1754
0
    if(xtype <= NC_NAT) return NC_EBADTYPE;
1755
    /* For compatibility, we need to allow inq about
1756
       atomic types, even if ncid is ill-defined */
1757
0
    if(xtype <= ATOMICTYPEMAX4) {
1758
0
        if(name) strncpy(name,NC_atomictypename(xtype),NC_MAX_NAME);
1759
0
        if(size) *size = NC_atomictypelen(xtype);
1760
0
        return NC_NOERR;
1761
0
    }
1762
    /* Apparently asking about a user defined type, so we need
1763
       a valid ncid */
1764
0
    stat = NC_check_id(ncid, &ncp);
1765
0
    if(stat != NC_NOERR) /* bad ncid */
1766
0
        return NC_EBADTYPE;
1767
    /* have good ncid */
1768
0
    return ncp->dispatch->inq_type(ncid,xtype,name,size);
1769
0
}
1770
1771
/** \defgroup dispatch dispatch functions. */
1772
/** \{
1773
1774
\ingroup dispatch
1775
*/
1776
1777
1778
/**
1779
   Check the create mode parameter for sanity.
1780
1781
   Some create flags cannot be used if corresponding library features are
1782
   enabled during the build. This function does a pre-check of the mode
1783
   flag before calling the dispatch layer nc_create functions.
1784
1785
   \param mode The creation mode flag.
1786
1787
   \returns ::NC_NOERR No error.
1788
   \returns ::NC_ENOTBUILT Requested feature not built into library
1789
   \returns ::NC_EINVAL Invalid combination of modes.
1790
   \internal
1791
   \ingroup dispatch
1792
   \author Ed Hartnett
1793
*/
1794
static int
1795
check_create_mode(int mode)
1796
0
{
1797
0
    int mode_format;
1798
0
    int use_mmap = 0;
1799
0
    int inmemory = 0;
1800
0
    int diskless = 0;
1801
1802
    /* This is a clever check to see if more than one format bit is
1803
     * set. */
1804
0
    mode_format = (mode & NC_NETCDF4) | (mode & NC_64BIT_OFFSET) |
1805
0
        (mode & NC_CDF5);
1806
0
    if (mode_format && (mode_format & (mode_format - 1)))
1807
0
        return NC_EINVAL;
1808
1809
0
    use_mmap = ((mode & NC_MMAP) == NC_MMAP);
1810
0
    inmemory = ((mode & NC_INMEMORY) == NC_INMEMORY);
1811
0
    diskless = ((mode & NC_DISKLESS) == NC_DISKLESS);
1812
1813
    /* NC_INMEMORY and NC_DISKLESS and NC_MMAP are all mutually exclusive */
1814
0
    if(diskless && inmemory) return NC_EDISKLESS;
1815
0
    if(diskless && use_mmap) return NC_EDISKLESS;
1816
0
    if(inmemory && use_mmap) return NC_EINMEMORY;
1817
1818
    /* mmap is not allowed for netcdf-4 */
1819
0
    if(use_mmap && (mode & NC_NETCDF4)) return NC_EINVAL;
1820
1821
#ifndef USE_NETCDF4
1822
    /* If the user asks for a netCDF-4 file, and the library was built
1823
     * without netCDF-4, then return an error.*/
1824
    if (mode & NC_NETCDF4)
1825
        return NC_ENOTBUILT;
1826
#endif /* USE_NETCDF4 undefined */
1827
1828
    /* Well I guess there is some sanity in the world after all. */
1829
0
    return NC_NOERR;
1830
0
}
1831
1832
/**
1833
 * @internal Create a file, calling the appropriate dispatch create
1834
 * call.
1835
 *
1836
 * For create, we have the following pieces of information to use to
1837
 * determine the dispatch table:
1838
 * - path
1839
 * - cmode
1840
 *
1841
 * @param path0 The file name of the new netCDF dataset.
1842
 * @param cmode The creation mode flag, the same as in nc_create().
1843
 * @param initialsz This parameter sets the initial size of the file
1844
 * at creation time. This only applies to classic
1845
 * files.
1846
 * @param basepe Deprecated parameter from the Cray days.
1847
 * @param chunksizehintp A pointer to the chunk size hint. This only
1848
 * applies to classic files.
1849
 * @param useparallel Non-zero if parallel I/O is to be used on this
1850
 * file.
1851
 * @param parameters Pointer to MPI comm and info.
1852
 * @param ncidp Pointer to location where returned netCDF ID is to be
1853
 * stored.
1854
 *
1855
 * @returns ::NC_NOERR No error.
1856
 * @ingroup dispatch
1857
 * @author Dennis Heimbigner, Ed Hartnett, Ward Fisher
1858
 */
1859
int
1860
NC_create(const char *path0, int cmode, size_t initialsz,
1861
          int basepe, size_t *chunksizehintp, int useparallel,
1862
          void* parameters, int *ncidp)
1863
0
{
1864
0
    int stat = NC_NOERR;
1865
0
    NC* ncp = NULL;
1866
0
    const NC_Dispatch* dispatcher = NULL;
1867
0
    char* path = NULL;
1868
0
    NCmodel model;
1869
0
    char* newpath = NULL;
1870
1871
0
    TRACE(nc_create);
1872
0
    if(path0 == NULL)
1873
0
        {stat = NC_EINVAL; goto done;}
1874
1875
    /* Check mode flag for sanity. */
1876
0
    if ((stat = check_create_mode(cmode))) goto done;
1877
1878
    /* Initialize the library. The available dispatch tables
1879
     * will depend on how netCDF was built
1880
     * (with/without netCDF-4, DAP, CDMREMOTE). */
1881
0
    if(!NC_initialized) {
1882
0
        if ((stat = nc_initialize())) goto done;
1883
0
    }
1884
1885
0
    {
1886
        /* Skip past any leading whitespace in path */
1887
0
        const unsigned char* p;
1888
0
        for(p=(const unsigned char*)path0;*p;p++) {if(*p > ' ') break;}
1889
0
        path = nulldup((const char*)p);
1890
0
    }
1891
1892
0
    memset(&model,0,sizeof(model));
1893
0
    newpath = NULL;
1894
0
    if((stat = NC_infermodel(path,&cmode,1,useparallel,NULL,&model,&newpath))) goto done;
1895
0
    if(newpath) {
1896
0
        nullfree(path);
1897
0
        path = newpath;
1898
0
        newpath = NULL;
1899
0
    }
1900
1901
0
    assert(model.format != 0 && model.impl != 0);
1902
1903
    /* Now, check for NC_ENOTBUILT cases limited to create (so e.g. HDF4 is not listed) */
1904
0
#ifndef USE_HDF5
1905
0
    if (model.impl == NC_FORMATX_NC4)
1906
0
    {stat = NC_ENOTBUILT; goto done;}
1907
0
#endif
1908
0
#ifndef USE_PNETCDF
1909
0
    if (model.impl == NC_FORMATX_PNETCDF)
1910
0
    {stat = NC_ENOTBUILT; goto done;}
1911
0
#endif
1912
#ifndef NETCDF_ENABLE_CDF5
1913
    if (model.impl == NC_FORMATX_NC3 && (cmode & NC_64BIT_DATA))
1914
    {stat = NC_ENOTBUILT; goto done;}
1915
#endif
1916
1917
    /* Figure out what dispatcher to use */
1918
0
    switch (model.impl) {
1919
#ifdef USE_HDF5
1920
    case NC_FORMATX_NC4:
1921
        dispatcher = HDF5_dispatch_table;
1922
        break;
1923
#endif
1924
#ifdef USE_PNETCDF
1925
    case NC_FORMATX_PNETCDF:
1926
        dispatcher = NCP_dispatch_table;
1927
        break;
1928
#endif
1929
0
#ifdef NETCDF_ENABLE_NCZARR
1930
0
    case NC_FORMATX_NCZARR:
1931
0
        dispatcher = NCZ_dispatch_table;
1932
0
  break;
1933
0
#endif
1934
0
    case NC_FORMATX_NC3:
1935
0
        dispatcher = NC3_dispatch_table;
1936
0
        break;
1937
0
    default:
1938
0
        {
1939
0
#ifdef USE_NETCDF4
1940
            /* UDF format constants are a range, so handle them here.
1941
             * Convert format constant to array index and validate. */
1942
0
            int udf_index = udf_formatx_to_index(model.impl);
1943
0
            if (udf_index >= 0) {
1944
                /* Get the dispatch table for this UDF slot */
1945
0
                dispatcher = UDF_dispatch_tables[udf_index];
1946
                /* Ensure the UDF format has been registered via nc_def_user_format() */
1947
0
                if (!dispatcher) {
1948
0
                    stat = NC_ENOTBUILT;
1949
0
                    goto done;
1950
0
                }
1951
0
                break;
1952
0
            }
1953
0
#endif /* USE_NETCDF4 */
1954
0
            stat = NC_ENOTNC;
1955
0
            goto done;
1956
0
        }
1957
0
    }
1958
1959
    /* Create the NC* instance and insert its dispatcher and model */
1960
0
    if((stat = new_NC(dispatcher,path,cmode,&ncp))) goto done;
1961
1962
    /* Add to list of known open files and define ext_ncid */
1963
0
    add_to_NCList(ncp);
1964
1965
    /* Assume create will fill in remaining ncp fields */
1966
0
    if ((stat = dispatcher->create(ncp->path, cmode, initialsz, basepe, chunksizehintp,
1967
0
                                   parameters, dispatcher, ncp->ext_ncid))) {
1968
0
        del_from_NCList(ncp); /* oh well */
1969
0
        free_NC(ncp);
1970
0
    } else {
1971
0
        if(ncidp)*ncidp = ncp->ext_ncid;
1972
0
    }
1973
0
done:
1974
0
    nullfree(path);
1975
0
    nullfree(newpath);
1976
0
    return stat;
1977
0
}
1978
1979
/**
1980
 * @internal Open a netCDF file (or remote dataset) calling the
1981
 * appropriate dispatch function.
1982
 *
1983
 * For open, we have the following pieces of information to use to
1984
 * determine the dispatch table.
1985
 * - table specified by override
1986
 * - path
1987
 * - omode
1988
 * - the contents of the file (if it exists), basically checking its magic number.
1989
 *
1990
 * @param path0 Path to the file to open.
1991
 * @param omode Open mode.
1992
 * @param basepe Base processing element (ignored).
1993
 * @param chunksizehintp Size hint for classic files.
1994
 * @param useparallel If true use parallel I/O.
1995
 * @param parameters Extra parameters for the open.
1996
 * @param ncidp Pointer that gets ncid.
1997
 *
1998
 * @returns ::NC_NOERR No error.
1999
 * @ingroup dispatch
2000
 * @author Dennis Heimbigner
2001
 */
2002
int
2003
NC_open(const char *path0, int omode, int basepe, size_t *chunksizehintp,
2004
        int useparallel, void* parameters, int *ncidp)
2005
77
{
2006
77
    int stat = NC_NOERR;
2007
77
    NC* ncp = NULL;
2008
77
    const NC_Dispatch* dispatcher = NULL;
2009
77
    int inmemory = 0;
2010
77
    int diskless = 0;
2011
77
    int use_mmap = 0;
2012
77
    char* path = NULL;
2013
77
    NCmodel model;
2014
77
    char* newpath = NULL;
2015
2016
77
    TRACE(nc_open);
2017
77
    if(!NC_initialized) {
2018
1
        stat = nc_initialize();
2019
1
        if(stat) goto done;
2020
1
    }
2021
2022
    /* Check inputs. */
2023
77
    if (!path0)
2024
0
        {stat = NC_EINVAL; goto done;}
2025
2026
    /* Capture the inmemory related flags */
2027
77
    use_mmap = ((omode & NC_MMAP) == NC_MMAP);
2028
77
    diskless = ((omode & NC_DISKLESS) == NC_DISKLESS);
2029
77
    inmemory = ((omode & NC_INMEMORY) == NC_INMEMORY);
2030
2031
    /* NC_INMEMORY and NC_DISKLESS and NC_MMAP are all mutually exclusive */
2032
77
    if(diskless && inmemory) {stat = NC_EDISKLESS; goto done;}
2033
77
    if(diskless && use_mmap) {stat = NC_EDISKLESS; goto done;}
2034
77
    if(inmemory && use_mmap) {stat = NC_EINMEMORY; goto done;}
2035
2036
    /* mmap is not allowed for netcdf-4 */
2037
77
    if(use_mmap && (omode & NC_NETCDF4)) {stat = NC_EINVAL; goto done;}
2038
2039
    /* Attempt to do file path conversion: note that this will do
2040
       nothing if path is a 'file:...' url, so it will need to be
2041
       repeated in protocol code (e.g. libdap2, libdap4, etc).
2042
    */
2043
2044
77
    {
2045
        /* Skip past any leading whitespace in path */
2046
77
        const char* p;
2047
77
        for(p=(const char*)path0;*p;p++) {if(*p < 0 || *p > ' ') break;}
2048
77
        path = nulldup(p);
2049
77
    }
2050
2051
77
    memset(&model,0,sizeof(model));
2052
    /* Infer model implementation and format, possibly by reading the file */
2053
77
    if((stat = NC_infermodel(path,&omode,0,useparallel,parameters,&model,&newpath)))
2054
7
        goto done;
2055
70
    if(newpath) {
2056
0
        nullfree(path);
2057
0
        path = newpath;
2058
0
  newpath = NULL;
2059
0
    }
2060
2061
    /* Still no implementation, give up */
2062
70
    if(model.impl == 0) {
2063
#ifdef DEBUG
2064
        fprintf(stderr,"implementation == 0\n");
2065
#endif
2066
0
        {stat = NC_ENOTNC; goto done;}
2067
0
    }
2068
2069
    /* Suppress unsupported formats */
2070
#if 0
2071
    /* (should be more compact, table-driven, way to do this) */
2072
    {
2073
  int hdf5built = 0;
2074
  int hdf4built = 0;
2075
  int cdf5built = 0;
2076
  int udf0built = 0;
2077
  int udf1built = 0;
2078
  int nczarrbuilt = 0;
2079
#ifdef USE_NETCDF4
2080
        hdf5built = 1;
2081
#endif
2082
#ifdef USE_HDF4
2083
        hdf4built = 1;
2084
#endif
2085
#ifdef NETCDF_ENABLE_CDF5
2086
        cdf5built = 1;
2087
#endif
2088
#ifdef NETCDF_ENABLE_NCZARR
2089
  nczarrbuilt = 1;
2090
#endif
2091
        if(!hdf5built && model.impl == NC_FORMATX_NC4)
2092
        {stat = NC_ENOTBUILT; goto done;}
2093
        if(!hdf4built && model.impl == NC_FORMATX_NC_HDF4)
2094
        {stat = NC_ENOTBUILT; goto done;}
2095
        if(!cdf5built && model.impl == NC_FORMATX_NC3 && model.format == NC_FORMAT_CDF5)
2096
        {stat = NC_ENOTBUILT; goto done;}
2097
  if(!nczarrbuilt && model.impl == NC_FORMATX_NCZARR)
2098
        {stat = NC_ENOTBUILT; goto done;}
2099
        /* If the model is a UDF format, ensure it has been registered.
2100
         * A UDF format is considered "built" if its dispatch table is non-NULL. */
2101
        {
2102
            int udf_index = udf_formatx_to_index(model.impl);
2103
            if(udf_index >= 0 && UDF_dispatch_tables[udf_index] == NULL)
2104
                {stat = NC_ENOTBUILT; goto done;}
2105
        }
2106
    }
2107
#else
2108
70
    {
2109
70
  unsigned built = 0 /* leave off the trailing semicolon so we can build constant */
2110
70
    | (1<<NC_FORMATX_NC3) /* NC3 always supported */
2111
#ifdef USE_HDF5
2112
    | (1<<NC_FORMATX_NC_HDF5)
2113
#endif
2114
#ifdef USE_HDF4
2115
    | (1<<NC_FORMATX_NC_HDF4)
2116
#endif
2117
70
#ifdef NETCDF_ENABLE_NCZARR
2118
70
    | (1<<NC_FORMATX_NCZARR)
2119
70
#endif
2120
#ifdef NETCDF_ENABLE_DAP
2121
    | (1<<NC_FORMATX_DAP2)
2122
#endif
2123
#ifdef NETCDF_ENABLE_DAP4
2124
    | (1<<NC_FORMATX_DAP4)
2125
#endif
2126
#ifdef USE_PNETCDF
2127
    | (1<<NC_FORMATX_PNETCDF)
2128
#endif
2129
70
    ; /* end of the built flags */
2130
        /* Verify the requested format is available. UDF format constants
2131
         * can exceed 31, so they cannot be checked with a bitmask; a UDF
2132
         * format is available iff its dispatch table is registered. */
2133
70
        {
2134
70
            int udf_index = udf_formatx_to_index(model.impl);
2135
70
            if(udf_index >= 0) {
2136
0
                if(UDF_dispatch_tables[udf_index] == NULL)
2137
0
                    {stat = NC_ENOTBUILT; goto done;}
2138
70
            } else if((built & (1U << model.impl)) == 0)
2139
0
                {stat = NC_ENOTBUILT; goto done;}
2140
70
        }
2141
#ifndef NETCDF_ENABLE_CDF5
2142
  /* Special case because there is no separate CDF5 dispatcher */
2143
        if(model.impl == NC_FORMATX_NC3 && (omode & NC_64BIT_DATA))
2144
            {stat = NC_ENOTBUILT; goto done;}
2145
#endif
2146
70
    }
2147
70
#endif
2148
    /* Figure out what dispatcher to use */
2149
70
    if (!dispatcher) {
2150
70
        switch (model.impl) {
2151
#ifdef NETCDF_ENABLE_DAP
2152
        case NC_FORMATX_DAP2:
2153
            dispatcher = NCD2_dispatch_table;
2154
            break;
2155
#endif
2156
#ifdef NETCDF_ENABLE_DAP4
2157
        case NC_FORMATX_DAP4:
2158
            dispatcher = NCD4_dispatch_table;
2159
            break;
2160
#endif
2161
0
#ifdef NETCDF_ENABLE_NCZARR
2162
0
  case NC_FORMATX_NCZARR:
2163
0
      dispatcher = NCZ_dispatch_table;
2164
0
      break;
2165
0
#endif
2166
#ifdef USE_PNETCDF
2167
        case NC_FORMATX_PNETCDF:
2168
            dispatcher = NCP_dispatch_table;
2169
            break;
2170
#endif
2171
#ifdef USE_HDF5
2172
        case NC_FORMATX_NC4:
2173
            dispatcher = HDF5_dispatch_table;
2174
            break;
2175
#endif
2176
#ifdef USE_HDF4
2177
        case NC_FORMATX_NC_HDF4:
2178
            dispatcher = HDF4_dispatch_table;
2179
            break;
2180
#endif
2181
70
        case NC_FORMATX_NC3:
2182
70
            dispatcher = NC3_dispatch_table;
2183
70
            break;
2184
0
        default:
2185
0
            {
2186
0
#ifdef USE_NETCDF4
2187
                /* UDF format constants are a range, so handle them here.
2188
                 * Convert format constant to array index and validate. */
2189
0
                int udf_index = udf_formatx_to_index(model.impl);
2190
0
                if (udf_index >= 0) {
2191
                    /* Get the dispatch table for this UDF slot */
2192
0
                    dispatcher = UDF_dispatch_tables[udf_index];
2193
                    /* Ensure the UDF format has been registered via nc_def_user_format() */
2194
0
                    if (!dispatcher) {
2195
0
                        stat = NC_ENOTBUILT;
2196
0
                        goto done;
2197
0
                    }
2198
0
                    break;
2199
0
                }
2200
0
#endif /* USE_NETCDF4 */
2201
0
                stat = NC_ENOTNC;
2202
0
                goto done;
2203
0
            }
2204
70
        }
2205
70
    }
2206
2207
2208
    /* If we can't figure out what dispatch table to use, give up. */
2209
70
    if (!dispatcher) {stat = NC_ENOTNC; goto done;}
2210
2211
    /* Create the NC* instance and insert its dispatcher */
2212
70
    if((stat = new_NC(dispatcher,path,omode,&ncp))) goto done;
2213
2214
    /* Add to list of known open files. This assigns an ext_ncid. */
2215
70
    add_to_NCList(ncp);
2216
2217
    /* Assume open will fill in remaining ncp fields */
2218
70
    stat = dispatcher->open(ncp->path, omode, basepe, chunksizehintp,
2219
70
                            parameters, dispatcher, ncp->ext_ncid);
2220
70
    if(stat == NC_NOERR) {
2221
5
        if(ncidp) *ncidp = ncp->ext_ncid;
2222
65
    } else {
2223
65
        del_from_NCList(ncp);
2224
65
        free_NC(ncp);
2225
65
    }
2226
2227
77
done:
2228
77
    nullfree(path);
2229
77
    nullfree(newpath);
2230
77
    return stat;
2231
70
}
2232
2233
/*Provide an internal function for generating pseudo file descriptors
2234
  for systems that are not file based (e.g. dap, memio).
2235
*/
2236
2237
/** @internal Static counter for pseudo file descriptors (incremented) */
2238
static int pseudofd = 0;
2239
2240
/**
2241
 * @internal Create a pseudo file descriptor that does not
2242
 * overlap real file descriptors
2243
 *
2244
 * @return pseudo file number
2245
 * @author Dennis Heimbigner
2246
 */
2247
int
2248
nc__pseudofd(void)
2249
70
{
2250
70
    if(pseudofd == 0)  {
2251
1
#ifdef HAVE_GETRLIMIT
2252
1
        int maxfd = 32767; /* default */
2253
1
        struct rlimit rl;
2254
1
        if(getrlimit(RLIMIT_NOFILE,&rl) == 0) {
2255
1
            if(rl.rlim_max != RLIM_INFINITY)
2256
1
                maxfd = (int)rl.rlim_max;
2257
1
            if(rl.rlim_cur != RLIM_INFINITY)
2258
1
                maxfd = (int)rl.rlim_cur;
2259
1
        }
2260
1
        pseudofd = maxfd+1;
2261
1
#endif
2262
1
    }
2263
70
    return pseudofd++;
2264
70
}
2265
/** \} */