Search code examples
coptimizationfile-iofwrite

How to write an unsigned long long integer value to a text file using fwrite()?


I need to write unsigned long long integer values to a text file. When I used fprintf() it works perfectly but, takes time. I have profiled my application and fprintf() takes the half of all time. I have made a research and I saw that, fwrite() is more effective than fprintf(). But I couldn't managed how to use it?

My code with fprintf()

fprintf(out, "%llu %llu\n", min, minv);

My code with fwrite()

fwrite(&min,sizeof(unsigned long long int),1, out);
fputs(" ",out);
fwrite(&minv,sizeof(unsigned long long int),1, out);
fputs("\n", out);

fwrite() is faster the first one but when I opened the file, the data is like

¾²ö㄀㄀㄀ `àÔàUü
ؾ{4-㄀㄀㄀ "¤#sÏ$P
 oD/㄀㄀㄀ 
-5X®Z

How could I perform fwrite() properly in this situation?


Solution

  • ... need to write unsigned long long integer values to a text file ...

    The typical method to write an unsigned long long is the below. Note that the file is open in text mode.

    out = fopen("data.out","w");
    fprintf(out, " %llu", x);
    

    To write faster, consider writing the text file file in binary mode. This will lose end-of-line translation, but may increase performance.

    out = fopen("data.out","wb");
    fprintf(out, " %llu", x);
    

    If the compiler is weak, converting the unsigned long long to a string may further improve. A non-standard conversion function is needed. Some ideas here

    out = fopen("data.out","wb");
    char buf[50];
    buf[0] = ' ';
    
    size_t size = my_ulltoa(&buf[1], x);  // returns size of the array used.
    fwrite(buf, 1, 1 + size, 1, out);
    

    OP's use of the below failed as it wrote a binary (e.g. 4 or 8 byte) representation to the text file, which is not readable as characters.

    out = fopen("data.out","w");
    // fails
    fwrite(&min,sizeof(unsigned long long int),1, out);
    

    Far faster is to write the binary representation to a binary file - but that is not readable as text.

    // Works for non-text files
    out = fopen("data.out","wb");
    fwrite(&min, sizeof min, 1, out);