Re: open an existing file in buffer and write on it



Hello,

Le 25/01/2013, Rudra Banerjee <rudra banerjee aol co uk> a Ãcrit :
What I have ended up with is something like:
  FILE *fopf = fopen(filename, "a" );
  if (!fopf){
    filename="Untitled.bib";
    fopf= fopen(filename,"a");
  }
  char buffer[]="Hello World";
  int buf_size= strlen(buffer)+1;
  fwrite(buffer,buf_size,1,fopf);
  if(!buffer){
    printf("failed");
  }
//  fclose(fopf);
I guess this part is first try, it's unnecessary when using
g_file_set_contents().

  GString *fop=g_string_new(NULL);
  g_string_append_printf( fop,buffer);

  gtk_label_set_text(GTK_LABEL(flabel), filename);
    g_string_append_printf( fop, "@%s{%s,\n", strcombo, strkey );
  if( strlen(strAuth)!=0)
    g_string_append_printf( fop, "\tAuthor=\"%s\",\n", strAuth);
  if( strlen(strEditor)!=0)
    g_string_append_printf( fop, "\tEditor=\"%s\",\n", strEditor);
  if( strlen(strSchool)!=0)
    g_string_append_printf( fop, "\tSchool=\"%s\",\n", strSchool);
    g_string_append_printf( fop, "}\n");
//  fclose(fop);
Up to here, I'm OK.

    g_file_set_contents(filename,
      fop,
      1026,
      NULL);
The issue is here, have a look to the API of GString. GString struct is
a wrapper on a string for it to auto expand. So fop is *not* the string
but the wrapper. So the call should be
success = g_file_set_contents(filename, fop->str, -1, &error);
the actual string contained in the GString wrapper is the ->str
attribute. The length is autmatic with -1 (because ->str is a zero
terminated char array) and you can catchup error if any (or not by
passing NULL as you did).

Remember to free the GString *and* the char array buffer by calling
g_string_free(fop, TRUE); (see the doc on the API page for the meaning
of TRUE).

Have a nice day,

Damien.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]