Search code examples
ccross-platform

How to make system calls cross-platform: maintainable and best practice


I have hundreds of system calls like this:

char buffer[MAX_LINE_LENGTH];

// ...

sprintf(buffer,"cat cgx_tmp.fbl >> cgx_tmp2.fbl");
system(buffer);
sprintf(buffer,"mv -f cgx_tmp2.fbl %s.fbl", datin);
system(buffer);
sprintf(buffer,"rm -f cgx_tmp.fbl");
system(buffer);

To fix the code, i.e. to make the system calls cross-platform, hundreds of OS-specific system calls like mv, rm, and cat might be modified like this:

#ifdef WIN32
    sprintf (buffer, "move /y \"%s\" \"%s.fbb\"", datin, setname );
#else
    sprintf (buffer, "mv %s %s.fbb", datin, setname );
#endif

Question

I just thought I'd ask before actually fixing the code. Is the above #ifdef approach acceptable? Is there any best practice to consider system calls for Windows OS or any other platforms?

If any other approaches are preferred, it would be great if you give some examples of them. So that I can use them as a reference for my fix. Thanks for your help.


Solution

  • It is one of the circumstances when I consider C source files inclusion correct.

    Have two or more files with commands for a particular system and include them

    #if defined(WIN32)
    #include "win.c"
    #else
    #include "linux.c"
    #endif