beginners c question. copy files with flush data .

Im writing a gtk program.
I have written a routine to copy a file. When using this
to copy a file to a flash disk the data is not copied immediately.
When the user pulls the flash disk out often there are no or empty files on it.
Is there a way to force the data to be flushed ?

I looked at fsync() but that requires an int ?

Does anyone have some code they could post to do what I want ?
Thanks for any help.

int copy_file(const gchar *from, const gchar *to)
{
  FILE *f_from, *f_to;
  char buf[512];
  int read;

  f_from = g_fopen(from, "rb");
  if (f_from == NULL)
    return -1;
  f_to = g_fopen(to, "w+b");
  if (f_to == NULL) {
    fclose(f_from);
    return -1;
  }

  read = fread(buf, 1, sizeof(buf), f_from);
  while (read > 0) {
    fwrite(buf, 1, read, f_to);
    read = fread(buf, 1, sizeof(buf), f_from);
  }

  fclose(f_from);
  fclose(f_to);
  return 0;
}
Last edited on
I'm not sure which OS you are running on, but when data is actually flushed to the hard drive, flash drive, or whatever is usually up to the operating system. I'm not familiar with gtk so I don't know what you specifically have at your disposal. If fsync() needs an int, and the int it needs is the actual file descriptor from fopen(), then you should be able to get that int by calling fileno( f_to ) -- like this:

1
2
3

fsync( fileno( f_to ) );
Last edited on
Doesn't closing the file trigger a flush? I wouldn't expect that to help. It sounds like the file system's not being unmounted.
KBW, yes I believe closing the file should trigger the OS to flush its buffers and write to disk. I agree: There seems to be a delay in the unmounting of the file system.
Topic archived. No new replies allowed.