Writing pointer contents into file

Hi,

I have a character pointer that points to 4000 bytes of valid data. I need to write these valid contents pointed to by this pointer into the file. I am looking for the most optimized way of doing this. I am using the below logic which seems trivial. Can anybody please suggest a better approach to accomplish the same?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* length is the number of valid bytes of data */
void parse_contents(const char *data, int length)
{
     int j = 0;
     char path[1024] = "/tmp/data.xml";
     FILE *fp = NULL;

     fp = fopen(path, "wb");

     if (NULL != fp)
     {
          for (j = 0; j < length; j++)
          {
               fprintf(fp, "%c", *data++);
          }
     }
     else
     {
          printf("Failed to open file\n");
     }

     if (NULL != fp)
     {
          fclose(fp);
          fp= NULL;
     }
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
void parse_contents(const char *data, int length)
{
    const char path[] = "/tmp/data.xml";
    FILE *fp = NULL;

    fp = fopen(path, "wb");
    if (fp)
    {
        fwrite(data, 1, length, fp);
        fclose(fp);
    }
}
@kbw
Thank you.
Topic archived. No new replies allowed.