Matlab Crahes upon fopen in Mex File

295 views Asked by At

I have a little experience with Matlab, but am new to the mex environment.

What I am trying to do is to save some values I compute to a txt file in my C routine.

For the sake of simplicity I am using the example arrayProduct.c from MathWork's Create C Source File guide here to elaborate.

I modified the example code in the following way:

void arrayProduct(double x, double *y, double *z, mwSize n)
{
  mwSize i;

  /* multiply each element y by x */
  FILE *f = NULL;
  f = fopen("log_test.csv", "rb");
  for (i=0; i<n; i++) 
  {
    z[i] = x * y[i];
    fprintf(f, "%g\n", z[i]);
  }
  fclose(f);
}

So I added the declaration of f, the fopen, the fprintf and the fclose commands. I am using MS Visual Studio C++ 2013 Professional (C) as a compiler and the code compiles just fine. Through uncommenting all my changes and introducing them bit by bit again I was able to find out that Matlab crashes at the fopen command.

I wasn't able to find useful help here or elsewhere, so any suggestions are very welcome. Thanks very much in advance!

Kind Regards

Philipp

2

There are 2 answers

0
rst On BEST ANSWER

Use w+ or r+ when using fopen, depending on what you want to do with the file and whethe you want to create it or simply open it.

From (http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm)

  • "r" Opens a file for reading. The file must exist.
  • "w" Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.
  • "a" Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.
  • "r+" Opens a file to update both reading and writing. The file must exist.
  • "w+" Creates an empty file for both reading and writing.
  • "a+" Opens a file for reading and appending.
1
PhilippD On

Thanks for the helpful comments, especially by RobertStettler! The problem was with the mode I opened the file with. it should rather be r+, w+ or a+.