At each iteration of a loop, I need to save an array to a .dat file. The array represents an n by 1 vector so I'd like the formatting to be one entry per line of the .dat file.
I know how to read in .dat files to C and save to an array but have never done the reverse before and unfortunately all of the sources I've come across so far seem to only show how to do the former.
1 Answer 1
In the simplest case there can be at least two variants for output data to *.dat files:
- User-friendly text file (must be your case).
- Raw binary data (guess, it is not your case).
In the first case you can use fprintf() from stdio.h to output data:
#include <stdio.h>
int fprintf(FILE *stream, const char *format, ...);
As you need one item per line - your format may looks like "%d\n", "%x" etc.
Sure, before writing data you need to open output file with fopen():
FILE *fopen(const char *path, const char *mode);
Afterwards you can close it with fclose():
int fclose(FILE *fp);
In the second case you can use just write():
#include <unistd.h>
ssize_t write(int fildes, const void *buf, size_t nbyte);
To open file descriptor you can use open(const char *path, int oflag,...) and to close - close(int fildes)
.datextension has no special significance. It can be a simple text file.read()towrite(), if textual - changescanf()toprintf().