1

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.

asked Nov 27, 2013 at 6:47
2
  • 2
    A .dat extension has no special significance. It can be a simple text file. Commented Nov 27, 2013 at 6:48
  • > "I know how to read in .dat files to C" - and what's the problem? If your files are binary, just cnahge read() to write(), if textual - change scanf() to printf(). Commented Nov 27, 2013 at 6:52

1 Answer 1

2

In the simplest case there can be at least two variants for output data to *.dat files:

  1. User-friendly text file (must be your case).
  2. 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)

answered Nov 27, 2013 at 6:53
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.