muffinman
muffinman

Reputation: 49

Characters missing when writing in file in C

I've searched all I could and I'm actually not sure how to look for an answer as it's pretty specific.

I have a function that checks if a file exists and if it doesn't, create it and writes some parameters in it. After that another function adds some data in the file. But the first line of data is missing the number of characters that are in the line created with the file.

The code looks like this (I'm only putting the parts I think are relevant, as it's pretty messy) :

the function that checks if the file exists is :

int check_datafile(char *fname, Par *par){
  char filename[64] = "data/";

  strcat(filename, fname);
  FILE* fdesc = NULL;

  fdesc = fopen(filename, "r");
  if (fdesc == NULL){
  fdesc = fopen(filename, "w");
  fprintf(fdesc,"%d %.3f \n", par -> L, par -> t);
  close(fdesc);
  }
  return 1;
}

Then the function that writes is :

void result_block(Par *par, double M, double M2, double M4, int ntot, char *fname)
{
  char filename[64] = "data/";

  strcat(filename, fname);
  FILE* fichier = NULL;

  fichier = fopen(filename, "a");

  if (fichier != NULL) // File should already exist
  {
    fprintf(fichier, "%.3f %.3f %.3f\n", M/ntot, M2/ntot, M4/ntot);
    fclose(fichier);
  }
  else
  {
    printf("Problem with the file : %s\n", filename);
    exit(0);
  }
}

They are called by

int initialize_mc(Par *par, int *spin) {
  int i, L2 = par->L * par->L;
  double T = par -> t;
  char *f2;
  double ex[1];
  ex[0] = exp(-2/T);

  if (!par->L) {
    printf("Give system size N!\n");
    return 0;
  }

  init_ran(par->seed);

  sprintf(fname, "%3.3d_%5.3f", par->L, par->t);

  check_datafile(fname, par);

  mc(par, spin, ex);

  return 1;
}

And the function result_block is called in the function mc.

Typically, I want the file to look like this :

16 2.210 
205.412 43371.160 2010463301.344
201.876 42319.600 1951381846.720
198.396 40897.632 1836904396.032
197.652 40743.856 1833699088.000
...

And it looks like this :

16 2.210 
371.160 2010463301.344
201.876 42319.600 1951381846.720
198.396 40897.632 1836904396.032
197.652 40743.856 1833699088.000
...

The the first line of data is cut by the same amount of characters that is in the first line of the file.

What can cause this problem?

Upvotes: 2

Views: 612

Answers (1)

Ewan Mellor
Ewan Mellor

Reputation: 6847

close(fdesc); needs to be fclose(fdesc);. When you use FILE * you are implicitly using a buffer on your output. You need to call fclose so that the buffer gets flushed.

By calling close you are actually casting your pointer to an int and closing some random file descriptor (which presumably fails most of the time). You're not closing the FILE * at all.

Upvotes: 3

Related Questions