Search code examples
cpointerscharc-stringsfwrite

Using fwrite with char*


How would one use fwrite to a file with a char*? If I want to append a char* to the end of a file with a newline after, would something like this be right? If you had a variable like:

char* c = "some string";

Would it be:

FILE *fp = fopen("file.txt", "ab");
fwrite(c, sizeof(char*), sizeof(c), fp);
fwrite("\n", sizeof(char), 1, fp);
close(fp);

I'm a bit confused about the 2nd fwrite statement. Is it sizeof(char*) or sizeof(char)? Should I also have sizeof(c) or is that incorrect? Any advice would be appreciated, thanks.


Solution

  • It is the first call of fwrite that is incorrect.

    fwrite(c, sizeof(char*), sizeof(c), fp);
    

    It should be written like for example

    fwrite(c, sizeof( char ), strlen( c ), fp);
    

    That is the string literal "some string" excluding its terminating zero character is written in the file.

    As for this call

    fwrite("\n", sizeof(char), 1, fp);
    

    then one character '\n' is written in the file fp.

    Note: the string literal "\n" is internally represented as a character array of two elements { '\n', '\0' }.

    The function is declared like

    size_t fwrite(const void * restrict ptr,
                  size_t size, 
                  size_t nmemb,
                  FILE * restrict stream);
    

    and according to the C Standard (7.21.8.2 The fwrite function)

    2 The fwrite function writes, from the array pointed to by ptr, up to nmemb elements whose size is specified by size, to the stream pointed to by stream. For each object, size calls are made to the fputc function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file position indicator for the stream (if defined) is advanced by the number of characters successfully written. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate.