Trouble copying, writing to file, writing to new string buffer and concatenating a string in C

70 Views Asked by At

Having trouble with operations to do with the above mentioned functions. I am however able to print the output using the printf(); function.
In an example to demo, we'll use the problematic write function which does not write anything to the created file.

void *problematic_write (void *arg) {
  char *host_match =(char *)arg;
  FILE *tmp_host = fopen("../tmp.txt", "arw+");
  if (tmp_host == NULL) {
    printf("Something went wrong creating file!");
    exit(EXIT_FAILURE);
  }
  printf("%s", host_match);
  fprintf(tmp_host, "%s", host_match);
}

Earlier...

start_index = match_2[0].rm_so;
host_len = (match_2[0].rm_eo) - start_index;
host_match = (char * )malloc(host_len);
sprintf(host_match, "%.*s", host_len - 6, &clientbuffer_main[start_index + 6]);
host_match[host_len - 6] = '\0';
pthread_create(&thread_id, NULL, problematic_write, (void *)host_match);
pthread_join(thread_id, NULL);

Basically i'm extracting the Host: part of a http request.

Output:

localhost:8080

but nothing written to the file!

This is just an example of one of the operations i'm having trouble with.

1

There are 1 best solutions below

8
nielsen On BEST ANSWER
  1. The file open mode "arw+" is not defined by the standard. Unless the implementation defines a behavior in this case, it is undefined behavior to use this mode.

  2. Writing a file with fwrite() does not necessarily cause the given data to be written immediately to the file. Instead, a file stream is normally buffered such that the data is first written to a buffer in RAM. On certain events, the buffer contents is written to the actual file. This can be forced by calling fflush() or fclose().

  3. The function is declared to return a pointer of type void *. However, there is no return statement.

With the use of the file in the OP function problematic_write(), it is sufficient to open in mode "a". Furthermore, the function ends without returning or saving the handle to the opened file. Thus, the file must be closed before returning. Finally, the function must be declared as void (or return a value):

void problematic_write (void *arg) {
  char *host_match =(char *)arg;
  FILE *tmp_host = fopen("../tmp.txt", "a");   // Open file with a defined mode
  if (tmp_host == NULL) {
    printf("Something went wrong creating file!");
    exit(EXIT_FAILURE);
  }
  printf("%s", host_match);
  fprintf(tmp_host, "%s", host_match);
  fclose(tmp_host);   // Close the file
}