Platform independent method to access command line in C?

356 Views Asked by At

On windows, the programmer could do something like: system("ls > outputFile.txt")

Is there a platform independent way to access the command line, or a least a way to determine which platform the program is being executed on (because calls for the same functionality vary quite a bit)?

enter image description here

2

There are 2 best solutions below

0
On

system() itself is a standard C function defined in stdlib.h. The way it interprets its argument, though, is not standard (e.g. ls in UNIX, dir in Windows/DOS, etc.). If you're really asking whether there's a platform-independent way to list the files in a directory, the answer is (unfortunately) no. Some libraries do provide portable (to some degree) implementations, most notably Boost: How can I get the list of files in a directory using C or C++?

7
On

The system(3) function is standard ANSI C, it's already platform-independent. Any conforming C implementation will allow you to call it to run the system default command line processor/shell application. Of course, the actual programs you can run will vary from system to system (e.g. dir only works on Windows, while ls usually works on Unix-like platforms).